diff options
Diffstat (limited to 'pki/base/common/src/com/netscape/cmscore')
179 files changed, 9123 insertions, 9732 deletions
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>\  </code>  (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>\  </code> + *  (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> + * "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. * <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("cn=123459,o=certificate repository,o=airius.com", + * 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("obj is: " + 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("failed to load {0}", 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" }, }; } |