KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > ejb > ca > store > LocalCertificateStoreSessionBean


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14 package org.ejbca.core.ejb.ca.store;
15
16 import java.math.BigInteger JavaDoc;
17 import java.security.cert.Certificate JavaDoc;
18 import java.security.cert.X509CRL JavaDoc;
19 import java.security.cert.X509Certificate JavaDoc;
20 import java.sql.Connection JavaDoc;
21 import java.sql.PreparedStatement JavaDoc;
22 import java.sql.ResultSet JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collection JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.HashSet JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Random JavaDoc;
31
32 import javax.ejb.CreateException JavaDoc;
33 import javax.ejb.EJBException JavaDoc;
34 import javax.ejb.FinderException JavaDoc;
35
36 import org.apache.commons.lang.StringUtils;
37 import org.apache.log4j.Logger;
38 import org.ejbca.core.ejb.BaseSessionBean;
39 import org.ejbca.core.ejb.JNDINames;
40 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal;
41 import org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome;
42 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocal;
43 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocalHome;
44 import org.ejbca.core.ejb.log.ILogSessionLocal;
45 import org.ejbca.core.ejb.log.ILogSessionLocalHome;
46 import org.ejbca.core.ejb.protect.TableProtectSessionLocal;
47 import org.ejbca.core.ejb.protect.TableProtectSessionLocalHome;
48 import org.ejbca.core.model.InternalResources;
49 import org.ejbca.core.model.SecConst;
50 import org.ejbca.core.model.authorization.AuthorizationDeniedException;
51 import org.ejbca.core.model.ca.certificateprofiles.CACertificateProfile;
52 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfile;
53 import org.ejbca.core.model.ca.certificateprofiles.CertificateProfileExistsException;
54 import org.ejbca.core.model.ca.certificateprofiles.EndUserCertificateProfile;
55 import org.ejbca.core.model.ca.certificateprofiles.HardTokenAuthCertificateProfile;
56 import org.ejbca.core.model.ca.certificateprofiles.HardTokenAuthEncCertificateProfile;
57 import org.ejbca.core.model.ca.certificateprofiles.HardTokenEncCertificateProfile;
58 import org.ejbca.core.model.ca.certificateprofiles.HardTokenSignCertificateProfile;
59 import org.ejbca.core.model.ca.certificateprofiles.OCSPSignerCertificateProfile;
60 import org.ejbca.core.model.ca.certificateprofiles.RootCACertificateProfile;
61 import org.ejbca.core.model.ca.crl.RevokedCertInfo;
62 import org.ejbca.core.model.ca.store.CRLInfo;
63 import org.ejbca.core.model.ca.store.CertReqHistory;
64 import org.ejbca.core.model.ca.store.CertificateInfo;
65 import org.ejbca.core.model.log.Admin;
66 import org.ejbca.core.model.log.LogConstants;
67 import org.ejbca.core.model.log.LogEntry;
68 import org.ejbca.core.model.protect.TableVerifyResult;
69 import org.ejbca.core.model.ra.UserDataVO;
70 import org.ejbca.util.CertTools;
71 import org.ejbca.util.JDBCUtil;
72 import org.ejbca.util.StringTools;
73
74 /**
75  * Stores certificate and CRL in the local database using Certificate and CRL Entity Beans.
76  * Uses JNDI name for datasource as defined in env 'Datasource' in ejb-jar.xml.
77  *
78  * @ejb.bean display-name="CertificateStoreSB"
79  * name="CertificateStoreSession"
80  * jndi-name="CertificateStoreSession"
81  * view-type="both"
82  * type="Stateless"
83  * transaction-type="Container"
84  *
85  * @ejb.transaction type="Supports"
86  *
87  * @weblogic.enable-call-by-reference True
88  *
89  * @ejb.env-entry description="JDBC datasource to be used"
90  * name="DataSource"
91  * type="java.lang.String"
92  * value="${datasource.jndi-name-prefix}${datasource.jndi-name}"
93  *
94  * @ejb.env-entry description="Enable or disable protection of database entrys"
95  * name="certSigning"
96  * type="java.lang.String"
97  * value="${protection.certprotect}"
98  *
99  * @ejb.ejb-external-ref description="The Certificate entity bean used to store and fetch certificates"
100  * view-type="local"
101  * ref-name="ejb/CertificateDataLocal"
102  * type="Entity"
103  * home="org.ejbca.core.ejb.ca.store.CertificateDataLocalHome"
104  * business="org.ejbca.core.ejb.ca.store.CertificateDataLocal"
105  * link="CertificateData"
106  *
107  * @ejb.ejb-external-ref description="The CRL entity bean used to store and fetch CRLs"
108  * view-type="local"
109  * ref-name="ejb/CRLDataLocal"
110  * type="Entity"
111  * home="org.ejbca.core.ejb.ca.store.CRLDataLocalHome"
112  * business="org.ejbca.core.ejb.ca.store.CRLDataLocal"
113  * link="CRLData"
114  *
115  * @ejb.ejb-external-ref description="The CertReqHistoryData Entity bean"
116  * view-type="local"
117  * ref-name="ejb/CertReqHistoryDataLocal"
118  * type="Entity"
119  * home="org.ejbca.core.ejb.ca.store.CertReqHistoryDataLocalHome"
120  * business="org.ejbca.core.ejb.ca.store.CertReqHistoryDataLocal"
121  * link="CertReqHistoryData"
122  *
123  * @ejb.ejb-external-ref description="The CertificateProfileData Entity bean"
124  * view-type="local"
125  * ref-name="ejb/CertificateProfileDataLocal"
126  * type="Entity"
127  * home="org.ejbca.core.ejb.ca.store.CertificateProfileDataLocalHome"
128  * business="org.ejbca.core.ejb.ca.store.CertificateProfileDataLocal"
129  * link="CertificateProfileData"
130  *
131  * @ejb.ejb-external-ref description="The Log session bean"
132  * view-type="local"
133  * ref-name="ejb/LogSessionLocal"
134  * type="Session"
135  * home="org.ejbca.core.ejb.log.ILogSessionLocalHome"
136  * business="org.ejbca.core.ejb.log.ILogSessionLocal"
137  * link="LogSession"
138  *
139  * @ejb.ejb-external-ref description="The Authorization session bean"
140  * view-type="local"
141  * ref-name="ejb/AuthorizationSessionLocal"
142  * type="Session"
143  * home="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome"
144  * business="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal"
145  * link="AuthorizationSession"
146  *
147  * @ejb.ejb-external-ref description="Publishers are configured to store certificates and CRLs in additional places from the main database.
148  * Publishers runs as local beans"
149  * view-type="local"
150  * ref-name="ejb/PublisherSessionLocal"
151  * type="Session"
152  * home="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocalHome"
153  * business="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocal"
154  * link="PublisherSession"
155  *
156  * @ejb.ejb-external-ref
157  * description="The table protection session bean"
158  * view-type="local"
159  * ref-name="ejb/TableProtectSessionLocal"
160  * type="Session"
161  * home="org.ejbca.core.ejb.protect.TableProtectSessionLocalHome"
162  * business="org.ejbca.core.ejb.protect.TableProtectSessionLocal"
163  * link="TableProtectSession"
164  *
165  * @ejb.home extends="javax.ejb.EJBHome"
166  * local-extends="javax.ejb.EJBLocalHome"
167  * local-class="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome"
168  * remote-class="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome"
169  *
170  * @ejb.interface extends="javax.ejb.EJBObject"
171  * local-extends="javax.ejb.EJBLocalObject"
172  * local-class="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal"
173  * remote-class="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote"
174  *
175  * @version $Id: LocalCertificateStoreSessionBean.java,v 1.28.2.2 2007/03/01 16:16:06 anatom Exp $
176  *
177  */

178 public class LocalCertificateStoreSessionBean extends BaseSessionBean {
179
180     /** Internal localization of logs and errors */
181     private static final InternalResources intres = InternalResources.getInstance();
182     
183     /**
184      * The home interface of Certificate entity bean
185      */

186     private CertificateDataLocalHome certHome = null;
187
188     /**
189      * The home interface of Certificate Type entity bean
190      */

191     private CertificateProfileDataLocalHome certprofilehome = null;
192
193     /**
194      * The home interface of CRL entity bean
195      */

196     private CRLDataLocalHome crlHome = null;
197     
198     /**
199      * The home interface of CertReqHistory entity bean
200      */

201     private CertReqHistoryDataLocalHome certReqHistoryHome = null;
202     
203
204     /**
205      * The local interface of the log session bean
206      */

207     private ILogSessionLocal logsession = null;
208
209     /**
210      * The local interface of the authorization session bean
211      */

212     private IAuthorizationSessionLocal authorizationsession = null;
213
214     /** The come interface of the protection session bean */
215     private TableProtectSessionLocalHome protecthome = null;
216     
217     /** If protection of database entries are enabled of not, default not */
218     private boolean protect = false;
219     
220     /**
221      * The local interface of the publisher session bean
222      */

223     private IPublisherSessionLocal publishersession = null;
224
225     final private CertificateDataUtil.Adapter adapter;
226     
227     public LocalCertificateStoreSessionBean() {
228         super();
229         adapter = new MyAdapter();
230     }
231     
232     /**
233      * Default create for SessionBean without any creation Arguments.
234      *
235      * @throws CreateException if bean instance can't be created
236      */

237     public void ejbCreate() throws CreateException JavaDoc {
238         crlHome = (CRLDataLocalHome) getLocator().getLocalHome(CRLDataLocalHome.COMP_NAME);
239         certHome = (CertificateDataLocalHome) getLocator().getLocalHome(CertificateDataLocalHome.COMP_NAME);
240         certReqHistoryHome = (CertReqHistoryDataLocalHome) getLocator().getLocalHome(CertReqHistoryDataLocalHome.COMP_NAME);
241         certprofilehome = (CertificateProfileDataLocalHome) getLocator().getLocalHome(CertificateProfileDataLocalHome.COMP_NAME);
242         String JavaDoc sign = getLocator().getString("java:comp/env/certSigning");
243         if (StringUtils.equalsIgnoreCase(sign, "true")) {
244             protect = true;
245             protecthome = (TableProtectSessionLocalHome) getLocator().getLocalHome(TableProtectSessionLocalHome.COMP_NAME);
246         }
247
248     }
249
250     /**
251      * Gets connection to log session bean
252      */

253     protected ILogSessionLocal getLogSession() {
254         if (logsession == null) {
255             try {
256                 ILogSessionLocalHome home = (ILogSessionLocalHome) getLocator().getLocalHome(ILogSessionLocalHome.COMP_NAME);
257                 logsession = home.create();
258             } catch (Exception JavaDoc e) {
259                 throw new EJBException JavaDoc(e);
260             }
261         }
262         return logsession;
263     } //getLogSession
264

265
266     /**
267      * Gets connection to authorization session bean
268      *
269      * @return Connection
270      */

271     private IAuthorizationSessionLocal getAuthorizationSession() {
272         if (authorizationsession == null) {
273             try {
274                 IAuthorizationSessionLocalHome home = (IAuthorizationSessionLocalHome) getLocator().getLocalHome(IAuthorizationSessionLocalHome.COMP_NAME);
275                 authorizationsession = home.create();
276             } catch (Exception JavaDoc e) {
277                 throw new EJBException JavaDoc(e);
278             }
279         }
280         return authorizationsession;
281     } //getAuthorizationSession
282

283     /**
284      * Gets connection to publisher session bean
285      *
286      * @return Connection
287      */

288     private IPublisherSessionLocal getPublisherSession() {
289         if (publishersession == null) {
290             try {
291                 IPublisherSessionLocalHome home = (IPublisherSessionLocalHome) getLocator().getLocalHome(IPublisherSessionLocalHome.COMP_NAME);
292                 publishersession = home.create();
293             } catch (Exception JavaDoc e) {
294                 throw new EJBException JavaDoc(e);
295             }
296         }
297         return publishersession;
298     } //getPublisherSession
299

300
301     /**
302      * Stores a certificate.
303      *
304      * @param incert The certificate to be stored.
305      * @param cafp Fingerprint (hex) of the CAs certificate.
306      * @param username username of end entity owning the certificate.
307      * @param status Status of the certificate (from CertificateData).
308      * @param type Type of certificate (CERTTYPE_ENDENTITY etc from CertificateDataBean).
309      * @return true if storage was successful.
310      * @ejb.transaction type="Required"
311      * @ejb.interface-method
312      */

313     public boolean storeCertificate(Admin admin, Certificate JavaDoc incert, String JavaDoc username, String JavaDoc cafp,
314                                     int status, int type) {
315         debug(">storeCertificate(" + cafp + ", " + status + ", " + type + ")");
316
317         try {
318             // Strip dangerous chars
319
username = StringTools.strip(username);
320
321             X509Certificate JavaDoc cert = (X509Certificate JavaDoc) incert;
322             CertificateDataPK pk = new CertificateDataPK();
323             pk.fingerprint = CertTools.getFingerprintAsString(cert);
324             CertificateDataLocal data1 = null;
325             data1 = certHome.create(cert);
326             data1.setUsername(username);
327             data1.setCaFingerprint(cafp);
328             data1.setStatus(status);
329             data1.setType(type);
330             String JavaDoc msg = intres.getLocalizedMessage("store.storecert");
331             getLogSession().log(admin, cert, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), username, (X509Certificate JavaDoc) incert, LogEntry.EVENT_INFO_STORECERTIFICATE, msg);
332             if (protect) {
333                 CertificateInfo entry = new CertificateInfo(data1.getFingerprint(), data1.getCaFingerprint(), data1.getSerialNumber(), data1.getIssuerDN(), data1.getSubjectDN(), data1.getStatus(), data1.getType(), data1.getExpireDate(), data1.getRevocationDate(), data1.getRevocationReason());
334                 TableProtectSessionLocal protect = protecthome.create();
335                 protect.protect(admin, entry);
336             }
337         } catch (Exception JavaDoc e) {
338             String JavaDoc msg = intres.getLocalizedMessage("store.errorstorecert");
339             getLogSession().log(admin, (X509Certificate JavaDoc) incert, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), username, (X509Certificate JavaDoc) incert, LogEntry.EVENT_ERROR_STORECERTIFICATE, msg);
340             throw new EJBException JavaDoc(e);
341         }
342         debug("<storeCertificate()");
343         return true;
344     } // storeCertificate
345

346     /**
347      * Stores a CRL
348      *
349      * @param incrl The DER coded CRL to be stored.
350      * @param cafp Fingerprint (hex) of the CAs certificate.
351      * @param number CRL number.
352      * @return true if storage was successful.
353      * @ejb.transaction type="Required"
354      * @ejb.interface-method
355      */

356     public boolean storeCRL(Admin admin, byte[] incrl, String JavaDoc cafp, int number) {
357         debug(">storeCRL(" + cafp + ", " + number + ")");
358
359         try {
360             X509CRL JavaDoc crl = CertTools.getCRLfromByteArray(incrl);
361             CRLDataLocal data1 = crlHome.create(crl, number);
362             data1.setCaFingerprint(cafp);
363             String JavaDoc msg = intres.getLocalizedMessage("store.storecrl", new Integer JavaDoc(number), CertTools.getFingerprintAsString(crl));
364             getLogSession().log(admin, crl.getIssuerDN().toString().hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_STORECRL, msg);
365         } catch (Exception JavaDoc e) {
366             String JavaDoc msg = intres.getLocalizedMessage("store.storecrl");
367             getLogSession().log(admin, LogConstants.INTERNALCAID, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_STORECRL, msg);
368             throw new EJBException JavaDoc(e);
369         }
370         debug("<storeCRL()");
371
372         return true;
373     } // storeCRL
374

375     /**
376      * Lists fingerprint (primary key) of ALL certificates in the database.
377      * NOTE: Caution should be taken with this method as execution may be very
378      * heavy indeed if many certificates exist in the database (imagine what happens if
379      * there are millinos of certificates in the DB!).
380      * Should only be used for testing purposes.
381      *
382      * @param admin Administrator performing the operation
383      * @param issuerdn the dn of the certificates issuer.
384      * @return Collection of fingerprints, i.e. Strings, reverse ordered by expireDate where last expireDate is first in array.
385      * @ejb.interface-method
386      */

387     public Collection JavaDoc listAllCertificates(Admin admin, String JavaDoc issuerdn) {
388         debug(">listAllCertificates()");
389         Connection JavaDoc con = null;
390         PreparedStatement JavaDoc ps = null;
391         ResultSet JavaDoc result = null;
392         String JavaDoc dn = CertTools.stringToBCDNString(issuerdn);
393         dn = StringTools.strip(dn);
394         try {
395             con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
396             ps = con.prepareStatement("select fingerprint, expireDate from CertificateData where issuerDN=? ORDER BY expireDate DESC");
397             ps.setString(1, dn);
398             result = ps.executeQuery();
399             ArrayList JavaDoc vect = new ArrayList JavaDoc();
400             while (result.next()) {
401                 vect.add(result.getString(1));
402             }
403             debug("<listAllCertificates()");
404             return vect;
405         } catch (Exception JavaDoc e) {
406             throw new EJBException JavaDoc(e);
407         } finally {
408             JDBCUtil.close(con, ps, result);
409         }
410     } // listAllCertificates
411

412     /**
413      * Lists fingerprint (primary key) of ALL certificates in the database.
414      * NOTE: Caution should be taken with this method as execution may be very heavy indeed if many certificates exist in the database (imagine what happens if there are millinos of certificates in the DB!).
415      * Should only be used for testing purposes.
416      * @param admin Administrator performing the operation
417      * @param issuerdn the dn of the certificates issuer.
418      * @return Collection of fingerprints, i.e. Strings, reverse ordered by expireDate where last expireDate is first in array.
419      *
420      * @ejb.interface-method
421      */

422     public Collection JavaDoc listRevokedCertificates(Admin admin, String JavaDoc issuerdn) {
423         debug(">listRevokedCertificates()");
424
425         Connection JavaDoc con = null;
426         PreparedStatement JavaDoc ps = null;
427         ResultSet JavaDoc result = null;
428         String JavaDoc dn = CertTools.stringToBCDNString(issuerdn);
429         dn = StringTools.strip(dn);
430         try {
431             // TODO:
432
// This should only list a few thousend certificates at a time, in case there
433
// are really many revoked certificates after some time...
434
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
435             ps = con.prepareStatement("select fingerprint from CertificateData where status=? and issuerDN=? ORDER BY expireDate DESC");
436             ps.setInt(1, CertificateDataBean.CERT_REVOKED);
437             ps.setString(2, dn);
438             result = ps.executeQuery();
439             ArrayList JavaDoc vect = new ArrayList JavaDoc();
440             while (result.next()) {
441                 vect.add(result.getString(1));
442             }
443             debug("<listRevokedCertificates()");
444             return vect;
445         } catch (Exception JavaDoc e) {
446             throw new EJBException JavaDoc(e);
447         } finally {
448             JDBCUtil.close(con, ps, result);
449         }
450     } // listRevokedCertificates
451

452     /**
453      * Lists certificates for a given subject signed by the given issuer.
454      *
455      * @param admin Administrator performing the operation
456      * @param subjectDN the DN of the subject whos certificates will be retrieved.
457      * @param issuerDN the dn of the certificates issuer.
458      * @return Collection of Certificates (java.security.cert.Certificate) in no specified order or an empty Collection.
459      * @throws EJBException if a communication or other error occurs.
460      * @ejb.interface-method
461      */

462     public Collection JavaDoc findCertificatesBySubjectAndIssuer(Admin admin, String JavaDoc subjectDN, String JavaDoc issuerDN) {
463         debug(">findCertificatesBySubjectAndIssuer(), dn='" + subjectDN + "' and issuer='" + issuerDN + "'");
464         // First make a DN in our well-known format
465
String JavaDoc dn = CertTools.stringToBCDNString(subjectDN);
466         dn = StringTools.strip(dn);
467         String JavaDoc issuerdn = CertTools.stringToBCDNString(issuerDN);
468         issuerdn = StringTools.strip(issuerdn);
469         debug("Looking for cert with (transformed)DN: " + dn);
470         try {
471             Collection JavaDoc coll = certHome.findBySubjectDNAndIssuerDN(dn, issuerdn);
472             Collection JavaDoc ret = new ArrayList JavaDoc();
473             if (coll != null) {
474                 Iterator JavaDoc iter = coll.iterator();
475                 while (iter.hasNext()) {
476                     ret.add(((CertificateDataLocal) iter.next()).getCertificate());
477                 }
478             }
479             debug("<findCertificatesBySubjectAndIssuer(), dn='" + subjectDN + "' and issuer='" + issuerDN + "'");
480             return ret;
481         } catch (javax.ejb.FinderException JavaDoc fe) {
482             throw new EJBException JavaDoc(fe);
483         }
484     } //findCertificatesBySubjectAndIssuer
485

486     /**
487      * Lists certificates for a given subject.
488      *
489      * @param admin Administrator performing the operation
490      * @param subjectDN the DN of the subject whos certificates will be retrieved.
491      * @return Collection of Certificates (java.security.cert.Certificate) in no specified order or an empty Collection.
492      * @ejb.interface-method
493      */

494     public Collection JavaDoc findCertificatesBySubject(Admin admin, String JavaDoc subjectDN) {
495         debug(">findCertificatesBySubjectAndIssuer(), dn='" + subjectDN + "'");
496         // First make a DN in our well-known format
497
String JavaDoc dn = CertTools.stringToBCDNString(subjectDN);
498         dn = StringTools.strip(dn);
499         debug("Looking for cert with (transformed)DN: " + dn);
500         try {
501             Collection JavaDoc coll = certHome.findBySubjectDN(dn);
502             Collection JavaDoc ret = new ArrayList JavaDoc();
503             if (coll != null) {
504                 Iterator JavaDoc iter = coll.iterator();
505                 while (iter.hasNext()) {
506                     ret.add(((CertificateDataLocal) iter.next()).getCertificate());
507                 }
508             }
509             debug("<findCertificatesBySubject(), dn='" + subjectDN + "'");
510             return ret;
511         } catch (javax.ejb.FinderException JavaDoc fe) {
512             throw new EJBException JavaDoc(fe);
513         }
514     } //findCertificatesBySubject
515

516     /**
517      * @ejb.interface-method
518      */

519     public Collection JavaDoc findCertificatesByExpireTime(Admin admin, Date JavaDoc expireTime) {
520         debug(">findCertificatesByExpireTime(), time=" + expireTime);
521         // First make expiretime in well know format
522
debug("Looking for certs that expire before: " + expireTime);
523
524         try {
525             Collection JavaDoc coll = certHome.findByExpireDate(expireTime.getTime());
526             Collection JavaDoc ret = new ArrayList JavaDoc();
527
528             if (coll != null) {
529                 Iterator JavaDoc iter = coll.iterator();
530
531                 while (iter.hasNext()) {
532                     ret.add(((CertificateDataLocal) iter.next()).getCertificate());
533                 }
534             }
535             debug("<findCertificatesByExpireTime(), time=" + expireTime);
536             return ret;
537         } catch (javax.ejb.FinderException JavaDoc fe) {
538             throw new EJBException JavaDoc(fe);
539         }
540     }
541
542     //findCertificatesByExpireTime
543

544     /**
545      * Finds usernames of users having certificate(s) expiring within a specified time and that has
546      * status active.
547      *
548      * @ejb.interface-method
549      */

550     public Collection JavaDoc findCertificatesByExpireTimeWithLimit(Admin admin, Date JavaDoc expiretime) {
551         debug(">findCertificatesByExpireTimeWithLimit");
552
553         Connection JavaDoc con = null;
554         PreparedStatement JavaDoc ps = null;
555         ResultSet JavaDoc result = null;
556         ArrayList JavaDoc returnval = new ArrayList JavaDoc();
557         long currentdate = new Date JavaDoc().getTime();
558
559         try {
560             con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
561             ps = con.prepareStatement("SELECT DISTINCT username FROM CertificateData WHERE expireDate>=? AND expireDate<? AND status=?");
562             ps.setLong(1, currentdate);
563             ps.setLong(2, expiretime.getTime());
564             ps.setInt(3, CertificateDataBean.CERT_ACTIVE);
565             result = ps.executeQuery();
566             while (result.next() && returnval.size() <= SecConst.MAXIMUM_QUERY_ROWCOUNT + 1) {
567                 if (result.getString(1) != null && !result.getString(1).equals(""))
568                     returnval.add(result.getString(1));
569             }
570             debug("<findCertificatesByExpireTimeWithLimit()");
571             return returnval;
572         } catch (Exception JavaDoc e) {
573             throw new EJBException JavaDoc(e);
574         } finally {
575             JDBCUtil.close(con, ps, result);
576         }
577     } //findCertificatesByExpireTimeWithLimit
578

579     /**
580      * Finds a certificate specified by issuer DN and serial number.
581      *
582      * @param admin Administrator performing the operation
583      * @param issuerDN issuer DN of the desired certificate.
584      * @param serno serial number of the desired certificate!
585      * @return Certificate if found or null
586      * @ejb.interface-method
587      */

588     public Certificate JavaDoc findCertificateByIssuerAndSerno(Admin admin, String JavaDoc issuerDN, BigInteger JavaDoc serno) {
589         return CertificateDataUtil.findCertificateByIssuerAndSerno(admin, issuerDN, serno, certHome, adapter);
590     } //findCertificateByIssuerAndSerno
591

592     /**
593      * Implements ICertificateStoreSession::findCertificatesByIssuerAndSernos.
594      * <p/>
595      * The method retrives all certificates from a specific issuer
596      * which are identified by list of serial numbers. The collection
597      * will be empty if the issuerDN is <tt>null</tt>/empty
598      * or the collection of serial numbers is empty.
599      *
600      * @param admin
601      * @param issuerDN the subjectDN of a CA certificate
602      * @param sernos a collection of certificate serialnumbers
603      * @return Collection a list of certificates; never <tt>null</tt>
604      * @ejb.interface-method
605      */

606     public Collection JavaDoc findCertificatesByIssuerAndSernos(Admin admin, String JavaDoc issuerDN, Collection JavaDoc sernos) {
607         debug(">findCertificateByIssuerAndSernos()");
608
609         Connection JavaDoc con = null;
610         PreparedStatement JavaDoc ps = null;
611         ResultSet JavaDoc result = null;
612         ArrayList JavaDoc vect = null;
613
614         if (null == admin) {
615             throw new IllegalArgumentException JavaDoc();
616         }
617
618
619         if (null == issuerDN || issuerDN.length() <= 0
620                 || null == sernos || sernos.isEmpty()) {
621             return new ArrayList JavaDoc();
622         }
623
624         String JavaDoc dn = CertTools.stringToBCDNString(issuerDN);
625         debug("Looking for cert with (transformed)DN: " + dn);
626
627         try {
628
629             final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
630             {
631                 Iterator JavaDoc iter = sernos.iterator();
632                 while (iter.hasNext()) {
633                     sb.append(", '");
634                     // Make sure this is really a BigInteger passed in as (untrusted param)
635
BigInteger JavaDoc serno = (BigInteger JavaDoc) iter.next();
636                     sb.append(serno.toString());
637                     sb.append("'");
638                 }
639             }
640             /*
641              * to save the repeating if-statement in the above
642              * Closure not to add ', ' as the first characters
643              * in the StringBuffer we remove the two chars here :)
644              */

645             sb.delete(0, ", ".length());
646             con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
647             ps = con.prepareStatement("SELECT DISTINCT fingerprint"
648                     + " FROM CertificateData WHERE"
649                     + " issuerDN = ?"
650                     + " AND serialNumber IN (" + sb.toString() + ")");
651             ps.setString(1, dn);
652             result = ps.executeQuery();
653
654             vect = new ArrayList JavaDoc();
655             while (result.next()) {
656                 Certificate JavaDoc cert = findCertificateByFingerprint(admin, result.getString(1));
657                 if (cert != null) {
658                     vect.add(cert);
659                 }
660             }
661
662             debug("<findCertificateByIssuerAndSernos()");
663             return vect;
664         } catch (Exception JavaDoc fe) {
665             throw new EJBException JavaDoc(fe);
666         } finally {
667             JDBCUtil.close(con, ps, result);
668         }
669     } // findCertificateByIssuerAndSernos
670

671     /**
672      * Finds certificate(s) for a given serialnumber.
673      *
674      * @param admin Administrator performing the operation
675      * @param serno the serialnumber of the certificate(s) that will be retrieved
676      * @return Certificate or null if none found.
677      * @ejb.interface-method
678      */

679     public Collection JavaDoc findCertificatesBySerno(Admin admin, BigInteger JavaDoc serno) {
680         debug(">findCertificateBySerno(), serno=" + serno);
681         try {
682             Collection JavaDoc coll = certHome.findBySerialNumber(serno.toString());
683             ArrayList JavaDoc ret = new ArrayList JavaDoc();
684
685             if (coll != null) {
686                 Iterator JavaDoc iter = coll.iterator();
687
688                 while (iter.hasNext()) {
689                     ret.add(((CertificateDataLocal) iter.next()).getCertificate());
690                 }
691             }
692
693             debug("<findCertificateBySerno(), serno=" + serno);
694
695             return ret;
696         } catch (javax.ejb.FinderException JavaDoc fe) {
697             throw new EJBException JavaDoc(fe);
698         }
699     } // findCertificateBySerno
700

701     /**
702      * Finds username for a given certificate serial number.
703      *
704      * @param admin Administrator performing the operation
705      * @param serno the serialnumber of the certificate to find username for.
706      * @return username or null if none found.
707      * @ejb.interface-method
708      */

709     public String JavaDoc findUsernameByCertSerno(Admin admin, BigInteger JavaDoc serno, String JavaDoc issuerdn) {
710         if (log.isDebugEnabled()) {
711             debug(">findUsernameByCertSerno(), serno: " + serno.toString(16) + ", issuerdn: " + issuerdn);
712         }
713         String JavaDoc dn = CertTools.stringToBCDNString(issuerdn);
714         try {
715             Collection JavaDoc coll = certHome.findByIssuerDNSerialNumber(dn, serno.toString());
716             String JavaDoc ret = null;
717
718             if (coll != null) {
719                 Iterator JavaDoc iter = coll.iterator();
720                 while (iter.hasNext()) {
721                     ret = ((CertificateDataLocal) iter.next()).getUsername();
722                 }
723             }
724             debug("<findUsernameByCertSerno(), ret=" + ret);
725             return ret;
726         } catch (javax.ejb.FinderException JavaDoc fe) {
727             throw new EJBException JavaDoc(fe);
728         }
729     } // findUsernameByCertSerno
730

731     /**
732      * Finds certificate(s) for a given usernaem.
733      *
734      * @param admin Administrator performing the operation
735      * @param username the usernaem of the certificate(s) that will be retrieved
736      * @return Collection of Certificates (in no specified order) or null if none found.
737      * @ejb.interface-method
738      */

739     public Collection JavaDoc findCertificatesByUsername(Admin admin, String JavaDoc username) {
740         debug(">findCertificateBySerno(), username=" + username);
741
742         try {
743             // Strip dangerous chars
744
username = StringTools.strip(username);
745
746             Collection JavaDoc coll = certHome.findByUsername(username);
747             ArrayList JavaDoc ret = new ArrayList JavaDoc();
748
749             if (coll != null) {
750                 Iterator JavaDoc iter = coll.iterator();
751                 while (iter.hasNext()) {
752                     ret.add(((CertificateDataLocal) iter.next()).getCertificate());
753                 }
754             }
755
756             debug("<findCertificateBySerno(), username=" + username);
757             return ret;
758         } catch (javax.ejb.FinderException JavaDoc fe) {
759             throw new EJBException JavaDoc(fe);
760         }
761     } // findCertificateByUsername
762

763     /**
764      * @ejb.interface-method
765      */

766     public CertificateInfo getCertificateInfo(Admin admin, String JavaDoc fingerprint) {
767         debug(">getCertificateInfo()");
768         CertificateInfo ret = null;
769
770         try {
771             CertificateDataLocal res = certHome.findByPrimaryKey(new CertificateDataPK(fingerprint));
772             ret = new CertificateInfo(res.getFingerprint(), res.getCaFingerprint(), res.getSerialNumber(), res.getIssuerDN(), res.getSubjectDN(),
773                     res.getStatus(), res.getType(), res.getExpireDate(), res.getRevocationDate(), res.getRevocationReason());
774             debug("<getCertificateInfo()");
775         } catch (FinderException JavaDoc fe) {
776             // Return null;
777
} catch (Exception JavaDoc e) {
778             String JavaDoc msg = intres.getLocalizedMessage("store.errorcertinfo", fingerprint);
779             log.error(msg);
780             throw new EJBException JavaDoc(e);
781         }
782         return ret;
783     } // getCertificateInfo
784

785     /**
786      * @ejb.interface-method
787      */

788     public Certificate JavaDoc findCertificateByFingerprint(Admin admin, String JavaDoc fingerprint) {
789         return CertificateDataUtil.findCertificateByFingerprint(admin, fingerprint, certHome, adapter);
790     } // findCertificateByFingerprint
791

792     /**
793      * Lists all active (status = 20) certificates of a specific type and if
794      * given from a specific issuer.
795      * <p/>
796      * The type is the bitwise OR value of the types listed
797      * int {@link org.ejbca.core.ejb.ca.store.CertificateDataBean}:<br>
798      * <ul>
799      * <li><tt>CERTTYPE_ENDENTITY</tt><br>
800      * An user or machine certificate, which identifies a subject.
801      * </li>
802      * <li><tt>CERTTYPE_CA</tt><br>
803      * A CA certificate which is <b>not</b> a root CA.
804      * </li>
805      * <li><tt>CERTTYPE_ROOTCA</tt><br>
806      * A Root CA certificate.
807      * </li>
808      * </ul>
809      * <p/>
810      * Usage examples:<br>
811      * <ol>
812      * <li>Get all root CA certificates
813      * <p/>
814      * <code>
815      * ...
816      * ICertificateStoreSessionRemote itf = ...
817      * Collection certs = itf.findCertificatesByType(adm,
818      * CertificateDataBean.CERTTYPE_ROOTCA,
819      * null);
820      * ...
821      * </code>
822      * </li>
823      * <li>Get all subordinate CA certificates for a specific
824      * Root CA. It is assumed that the <tt>subjectDN</tt> of the
825      * Root CA certificate is located in the variable <tt>issuer</tt>.
826      * <p/>
827      * <code>
828      * ...
829      * ICertificateStoreSessionRemote itf = ...
830      * Certficate rootCA = ...
831      * String issuer = rootCA.getSubjectDN();
832      * Collection certs = itf.findCertificatesByType(adm,
833      * CertificateDataBean.CERTTYPE_SUBCA,
834      * issuer);
835      * ...
836      * </code>
837      * </li>
838      * <li>Get <b>all</b> CA certificates.
839      * <p/>
840      * <code>
841      * ...
842      * ICertificateStoreSessionRemote itf = ...
843      * Collection certs = itf.findCertificatesByType(adm,
844      * CertificateDataBean.CERTTYPE_SUBCA
845      * + CERTTYPE_ROOTCA,
846      * null);
847      * ...
848      * </code>
849      * </li>
850      * </ol>
851      *
852      * @param admin
853      * @param issuerDN get all certificates issued by a specific issuer.
854      * If <tt>null</tt> or empty return certificates regardless of
855      * the issuer.
856      * @param type CERTTYPE_* types from CertificateDataBean
857      * @return Collection Collection of X509Certificate, never <tt>null</tt>
858      * @ejb.interface-method
859      */

860     public Collection JavaDoc findCertificatesByType(Admin admin, int type, String JavaDoc issuerDN) {
861         return CertificateDataUtil.findCertificatesByType(admin, type, issuerDN, certHome, adapter);
862     } // findCertificatesByType
863

864     /**
865      * Set the status of certificates of given dn to revoked.
866      *
867      * @param admin Administrator performing the operation
868      * @param username the username of user to revoke certificates.
869      * @param publishers and array of publiserids (Integer) of publishers to revoke the certificate in.
870      * @param reason the reason of the revokation. (One of the RevokedCertInfo.REVOKATION_REASON
871      * constants.)
872      * @ejb.transaction type="Required"
873      * @ejb.interface-method
874      */

875     public void setRevokeStatus(Admin admin, String JavaDoc username, Collection JavaDoc publishers, int reason) {
876         debug(">setRevokeStatus(), username=" + username);
877         // Strip dangerous chars
878
username = StringTools.strip(username);
879         try {
880             Collection JavaDoc certs = findCertificatesByUsername(admin, username);
881             // Revoke all certs
882
if (!certs.isEmpty()) {
883                 Iterator JavaDoc j = certs.iterator();
884                 while (j.hasNext()) {
885                     setRevokeStatus(admin, (X509Certificate JavaDoc) j.next(), publishers, reason);
886                 }
887             }
888         } catch (FinderException JavaDoc e) {
889             String JavaDoc msg = intres.getLocalizedMessage("store.errorfindcertuser", username);
890             getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_REVOKEDCERT, msg);
891             throw new EJBException JavaDoc(e);
892         }
893         debug("<setRevokeStatus(), username=" + username);
894     } // setRevokeStatus
895

896     /**
897      * Set the status of certificate with given serno to revoked.
898      *
899      * @param admin Administrator performing the operation
900      * @param serno the serno of certificate to revoke.
901      * @param publishers and array of publiserids (Integer) of publishers to revoke the certificate in.
902      * @param reason the reason of the revokation. (One of the RevokedCertInfo.REVOKATION_REASON constants.)
903      * @ejb.transaction type="Required"
904      * @ejb.interface-method
905      */

906     public void setRevokeStatus(Admin admin, String JavaDoc issuerdn, BigInteger JavaDoc serno, Collection JavaDoc publishers, int reason) {
907         debug(">setRevokeStatus(), issuerdn=" + issuerdn + ", serno=" + serno);
908         X509Certificate JavaDoc certificate = null;
909         try {
910             certificate = (X509Certificate JavaDoc) this.findCertificateByIssuerAndSerno(admin, issuerdn, serno);
911             setRevokeStatus(admin, certificate, publishers, reason);
912         } catch (FinderException JavaDoc e) {
913             String JavaDoc msg = intres.getLocalizedMessage("store.errorfindcertserno", serno.toString(16));
914             getLogSession().log(admin, issuerdn.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_REVOKEDCERT, msg);
915             throw new EJBException JavaDoc(e);
916         }
917         debug("<setRevokeStatus(), issuerdn=" + issuerdn + ", serno=" + serno);
918     } // setRevokeStatus
919

920     /**
921      * Helper method to set the status of certificate to revoked or active.
922      *
923      * @param admin Administrator performing the operation
924      * @param certificate the certificate to revoke or activate.
925      * @param publishers and array of publiserids (Integer) of publishers to revoke/re-publish the certificate in.
926      * @param reason the reason of the revokation. (One of the RevokedCertInfo.REVOKATION_REASON constants.)
927      * @throws FinderException
928      */

929     private void setRevokeStatus(Admin admin, X509Certificate JavaDoc certificate, Collection JavaDoc publishers, int reason) throws FinderException JavaDoc {
930         if (certificate == null) {
931             return;
932         }
933         debug(">setRevokeStatus(X509Certificate), issuerdn=" + certificate.getIssuerDN() + ", serno=" + certificate.getSerialNumber());
934
935         if (certificate != null) {
936             CertificateDataPK revpk = new CertificateDataPK();
937             revpk.fingerprint = CertTools.getFingerprintAsString(certificate);
938             CertificateDataLocal rev = certHome.findByPrimaryKey(revpk);
939             String JavaDoc serialNo = certificate.getSerialNumber().toString(16); // for logging
940
if ( (rev.getStatus() != CertificateDataBean.CERT_REVOKED)
941                     && (reason != RevokedCertInfo.NOT_REVOKED) && (reason != RevokedCertInfo.REVOKATION_REASON_REMOVEFROMCRL) ) {
942                   rev.setStatus(CertificateDataBean.CERT_REVOKED);
943                   rev.setRevocationDate(new Date JavaDoc());
944                   rev.setRevocationReason(reason);
945                   String JavaDoc msg = intres.getLocalizedMessage("store.revokedcert", new Integer JavaDoc(reason));
946                   getLogSession().log(admin, certificate, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, certificate, LogEntry.EVENT_INFO_REVOKEDCERT, msg);
947                   // Revoke in all related publishers
948
if (publishers != null) {
949                       getPublisherSession().revokeCertificate(admin, publishers, certificate, reason);
950                   }
951             } else if ( ((reason == RevokedCertInfo.NOT_REVOKED) || (reason == RevokedCertInfo.REVOKATION_REASON_REMOVEFROMCRL))
952                     && (rev.getRevocationReason() == RevokedCertInfo.REVOKATION_REASON_CERTIFICATEHOLD) ) {
953                 // Only allow unrevocation if the certificate is revoked and the revocation reason is CERTIFICATE_HOLD
954
rev.setStatus(CertificateDataBean.CERT_ACTIVE);
955                 rev.setRevocationDate(null);
956                 rev.setRevocationReason(RevokedCertInfo.NOT_REVOKED);
957                 // Republish the certificate if possible
958
// If it is not possible, only log error but continue the operation of not revoking the certificate
959
try {
960                     CertReqHistory certreqhist = getCertReqHistory(admin, certificate.getSerialNumber(), certificate.getIssuerDN().getName());
961                     if(certreqhist == null){
962                         throw new Exception JavaDoc("Unrevoked cert:" + serialNo + " reason: " + reason + " Must not be republished.");
963                     }
964                     UserDataVO userdata = certreqhist.getUserDataVO();
965                     if ( userdata == null ){
966                         throw new Exception JavaDoc("Unrevoked cert:" + serialNo + " reason: " + reason + " Could not be republished, there ane no UserData in History.");
967                     }
968                     CertificateProfile certprofile = getCertificateProfile(admin, userdata.getCertificateProfileId());
969                     if(certprofile == null){
970                         throw new Exception JavaDoc("Unrevoked cert:" + serialNo + " reason: " + reason + " Could not be republished, can't find certificate profile.");
971                     }
972                     CertificateInfo certinfo = getCertificateInfo(admin, CertTools.getFingerprintAsString(certificate));
973                     if(certprofile.getPublisherList().size() <= 0){
974                         throw new Exception JavaDoc("Unrevoked cert:" + serialNo + " reason: " + reason + " Could not be republished, there are no publishers defined.");
975                     }
976                     boolean published = publishersession.storeCertificate(admin, certprofile.getPublisherList(), certificate, certreqhist.getUserDataVO().getUsername(), certreqhist.getUserDataVO().getPassword(),
977                             certinfo.getCAFingerprint(), certinfo.getStatus() , certinfo.getType(), certinfo.getRevocationDate().getTime(), certinfo.getRevocationReason(), certreqhist.getUserDataVO().getExtendedinformation());
978                     if ( !published ) {
979                         throw new Exception JavaDoc("Unrevoked cert:" + serialNo + " reason: " + reason + " Could not be republished.");
980                     }
981                     String JavaDoc msg = intres.getLocalizedMessage("store.republishunrevokedcert", new Integer JavaDoc(reason));
982                     getLogSession().log(admin, certificate.getIssuerDN().hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, certificate, LogEntry.EVENT_INFO_NOTIFICATION, msg);
983                 } catch (Exception JavaDoc ex) {
984                     // We catch the exception thrown above, to log the message, but it is only informational, so we dont re-throw anything
985
getLogSession().log(admin, certificate.getIssuerDN().hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, certificate, LogEntry.EVENT_INFO_NOTIFICATION, ex.getMessage());
986                 }
987             } else {
988                 String JavaDoc msg = intres.getLocalizedMessage("store.ignorerevoke", serialNo, new Integer JavaDoc(rev.getStatus()), new Integer JavaDoc(reason));
989                 getLogSession().log(admin, certificate.getIssuerDN().hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, certificate, LogEntry.EVENT_INFO_NOTIFICATION, msg);
990             }
991             // Update database protection
992
if (protect) {
993                 CertificateInfo entry = new CertificateInfo(rev.getFingerprint(), rev.getCaFingerprint(), rev.getSerialNumber(), rev.getIssuerDN(), rev.getSubjectDN(), rev.getStatus(), rev.getType(), rev.getExpireDate(), rev.getRevocationDate(), rev.getRevocationReason());
994                 TableProtectSessionLocal protect;
995                 try {
996                     protect = protecthome.create();
997                     protect.protect(admin, entry);
998                 } catch (CreateException JavaDoc e) {
999                     String JavaDoc msg = intres.getLocalizedMessage("protect.errorcreatesession");
1000                    error(msg, e);
1001                }
1002            }
1003
1004        }
1005        
1006        debug("<setRevokeStatus(), issuerdn=" + certificate.getIssuerDN() + ", serno=" + certificate.getSerialNumber());
1007    } // setRevokeStatus
1008

1009    /**
1010     * Revokes a certificate (already revoked by the CA), in the database
1011     *
1012     * @param cert The DER coded Certificate that has been revoked.
1013     * @param publishers and array of publiserids (Integer) of publishers to revoke the certificate in.
1014     * @ejb.transaction type="Required"
1015     * @ejb.interface-method
1016     */

1017    public void revokeCertificate(Admin admin, Certificate JavaDoc cert, Collection JavaDoc publishers, int reason) {
1018        if (cert instanceof X509Certificate JavaDoc) {
1019            setRevokeStatus(admin, ((X509Certificate JavaDoc) cert).getIssuerDN().toString(), ((X509Certificate JavaDoc) cert).getSerialNumber(), publishers, reason);
1020        }
1021    } //revokeCertificate
1022

1023    /**
1024     * Method revoking all certificates generated by the specified issuerdn. Sets revokedate to current time.
1025     * Should only be called by CAAdminBean when a CA is about to be revoked.
1026     *
1027     * @param admin the administrator performing the event.
1028     * @param issuerdn the dn of CA about to be revoked
1029     * @param reason the reason of revokation.
1030     * @ejb.transaction type="Required"
1031     * @ejb.interface-method
1032     */

1033    public void revokeAllCertByCA(Admin admin, String JavaDoc issuerdn, int reason) {
1034        Connection JavaDoc con = null;
1035        PreparedStatement JavaDoc ps = null;
1036        PreparedStatement JavaDoc ps2 = null;
1037        int temprevoked = 0;
1038        int revoked = 0;
1039
1040        String JavaDoc bcdn = CertTools.stringToBCDNString(issuerdn);
1041
1042        final String JavaDoc firstsqlstatement = "UPDATE CertificateData SET status=?" +
1043                " WHERE issuerDN=? AND status = ? ";
1044        final String JavaDoc secondsqlstatement = "UPDATE CertificateData SET status=?, revocationDate=?, revocationReason=?" +
1045                " WHERE issuerDN=? AND status <> ?";
1046
1047        long currentdate = new Date JavaDoc().getTime();
1048
1049        try {
1050            // First SQL statement, changing all temporaty revoked certificates to permanently revoked certificates
1051
con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1052            ps = con.prepareStatement(firstsqlstatement);
1053            ps.setInt(1, CertificateDataBean.CERT_REVOKED); // first statusfield
1054
ps.setString(2, bcdn); // issuerdn field
1055
ps.setInt(3, CertificateDataBean.CERT_TEMP_REVOKED); // second statusfield
1056
temprevoked = ps.executeUpdate();
1057
1058            // Second SQL statement, revoking all non revoked certificates.
1059
ps2 = con.prepareStatement(secondsqlstatement);
1060            ps2.setInt(1, CertificateDataBean.CERT_REVOKED); // first statusfield
1061
ps2.setLong(2, currentdate); // revokedate field
1062
ps2.setInt(3, reason); // revokation reason
1063
ps2.setString(4, bcdn); // issuer dn
1064
ps2.setInt(5, CertificateDataBean.CERT_REVOKED); // second statusfield
1065

1066            revoked = ps2.executeUpdate();
1067
1068            String JavaDoc msg = intres.getLocalizedMessage("store.revokedallbyca", issuerdn, new Integer JavaDoc(revoked + temprevoked), new Integer JavaDoc(reason));
1069            getLogSession().log(admin, bcdn.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_REVOKEDCERT, msg);
1070        } catch (Exception JavaDoc e) {
1071            String JavaDoc msg = intres.getLocalizedMessage("store.errorrevokeallbyca", issuerdn);
1072            getLogSession().log(admin, bcdn.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_REVOKEDCERT, msg, e);
1073            throw new EJBException JavaDoc(e);
1074        } finally {
1075            JDBCUtil.close(con, ps, null);
1076            JDBCUtil.close(ps2);
1077        }
1078    } // revokeAllCertByCA
1079

1080    /**
1081     * Method that checks if a users all certificates have been revoked.
1082     *
1083     * @param admin Administrator performing the operation
1084     * @param username the username to check for.
1085     * @return returns true if all certificates are revoked.
1086     * @ejb.interface-method
1087     */

1088    public boolean checkIfAllRevoked(Admin admin, String JavaDoc username) {
1089        boolean returnval = true;
1090        X509Certificate JavaDoc certificate = null;
1091        // Strip dangerous chars
1092
username = StringTools.strip(username);
1093        try {
1094            Collection JavaDoc certs = findCertificatesByUsername(admin, username);
1095            // Revoke all certs
1096
if (!certs.isEmpty()) {
1097                Iterator JavaDoc j = certs.iterator();
1098                while (j.hasNext()) {
1099                    CertificateDataPK revpk = new CertificateDataPK();
1100                    certificate = (X509Certificate JavaDoc) j.next();
1101                    revpk.fingerprint = CertTools.getFingerprintAsString(certificate);
1102                    CertificateDataLocal rev = certHome.findByPrimaryKey(revpk);
1103                    if (protect) {
1104                        CertificateInfo entry = new CertificateInfo(rev.getFingerprint(), rev.getCaFingerprint(), rev.getSerialNumber(), rev.getIssuerDN(), rev.getSubjectDN(), rev.getStatus(), rev.getType(), rev.getExpireDate(), rev.getRevocationDate(), rev.getRevocationReason());
1105                        TableProtectSessionLocal protect;
1106                        try {
1107                            protect = protecthome.create();
1108                            // The verify method will log failed verifies itself
1109
TableVerifyResult res = protect.verify(entry);
1110                            if (res.getResultCode() != TableVerifyResult.VERIFY_SUCCESS) {
1111                                //error("Verify failed, but we go on anyway.");
1112
}
1113                        } catch (CreateException JavaDoc e) {
1114                            String JavaDoc msg = intres.getLocalizedMessage("protect.errorcreatesession");
1115                            error(msg, e);
1116                        }
1117                    }
1118                    if (rev.getStatus() != CertificateDataBean.CERT_REVOKED) {
1119                        returnval = false;
1120                    }
1121                }
1122            }
1123
1124        } catch (FinderException JavaDoc e) {
1125            throw new EJBException JavaDoc(e);
1126        }
1127
1128        return returnval;
1129    }
1130
1131    /**
1132     * Checks if a certificate is revoked.
1133     *
1134     * @param admin Administrator performing the operation
1135     * @param issuerDN the DN of the issuer.
1136     * @param serno the serialnumber of the certificate that will be checked
1137     * @return RevokedCertInfo with revocation information, with reason RevokedCertInfo.NOT_REVOKED if NOT revoked. Returns null if certificate is not found.
1138     * @ejb.interface-method
1139     */

1140    public RevokedCertInfo isRevoked(Admin admin, String JavaDoc issuerDN, BigInteger JavaDoc serno) {
1141        return CertificateDataUtil.isRevoked(admin, issuerDN, serno, certHome, protecthome, adapter);
1142    } //isRevoked
1143

1144    /**
1145     * Retrieves the latest CRL issued by this CA.
1146     *
1147     * @param admin Administrator performing the operation
1148     * @param issuerdn the CRL issuers DN (CAs subject DN)
1149     * @return X509CRL or null of no CRLs have been issued.
1150     * @ejb.interface-method
1151     */

1152    public byte[] getLastCRL(Admin admin, String JavaDoc issuerdn) {
1153        debug(">getLastCRL(" + issuerdn + ")");
1154
1155        try {
1156            int maxnumber = getLastCRLNumber(admin, issuerdn);
1157            X509CRL JavaDoc crl = null;
1158            try {
1159                CRLDataLocal data = crlHome.findByIssuerDNAndCRLNumber(issuerdn, maxnumber);
1160                crl = data.getCRL();
1161            } catch (FinderException JavaDoc e) {
1162                crl = null;
1163            }
1164            debug("<getLastCRL()");
1165            if (crl == null)
1166                return null;
1167
1168            String JavaDoc msg = intres.getLocalizedMessage("store.getcrl", issuerdn, new Integer JavaDoc(maxnumber));
1169            getLogSession().log(admin, crl.getIssuerDN().toString().hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_GETLASTCRL, msg);
1170            return crl.getEncoded();
1171        } catch (Exception JavaDoc e) {
1172            String JavaDoc msg = intres.getLocalizedMessage("store.errorgetcrl", issuerdn);
1173            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_GETLASTCRL, msg);
1174            throw new EJBException JavaDoc(e);
1175        }
1176    } //getLastCRL
1177

1178    /**
1179     * Retrieves the information about the lastest CRL issued by this CA.
1180     *
1181     * @param admin Administrator performing the operation
1182     * @param issuerdn the CRL issuers DN (CAs subject DN)
1183     * @return CRLInfo of last CRL by CA.
1184     * @ejb.interface-method
1185     */

1186    public CRLInfo getLastCRLInfo(Admin admin, String JavaDoc issuerdn) {
1187        debug(">getLastCRLInfo(" + issuerdn + ")");
1188        try {
1189            int maxnumber = getLastCRLNumber(admin, issuerdn);
1190            CRLInfo crlinfo = null;
1191            try {
1192                CRLDataLocal data = crlHome.findByIssuerDNAndCRLNumber(issuerdn, maxnumber);
1193                crlinfo = new CRLInfo(data.getIssuerDN(), maxnumber, data.getThisUpdate(), data.getNextUpdate());
1194            } catch (FinderException JavaDoc e) {
1195                String JavaDoc msg = intres.getLocalizedMessage("store.errorgetcrl", issuerdn, new Integer JavaDoc(maxnumber));
1196                log.error(msg, e);
1197                crlinfo = null;
1198            }
1199            debug("<getLastCRLInfo()");
1200            return crlinfo;
1201        } catch (Exception JavaDoc e) {
1202            String JavaDoc msg = intres.getLocalizedMessage("store.errorgetcrlinfo", issuerdn);
1203            getLogSession().log(admin, issuerdn.hashCode(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_GETLASTCRL, msg);
1204            throw new EJBException JavaDoc(e);
1205        }
1206    } //getLastCRL
1207

1208    /**
1209     * Retrieves the highest CRLNumber issued by the CA.
1210     *
1211     * @param admin Administrator performing the operation
1212     * @param issuerdn the subjectDN of a CA certificate
1213     * @ejb.interface-method
1214     */

1215    public int getLastCRLNumber(Admin admin, String JavaDoc issuerdn) {
1216        debug(">getLastCRLNumber(" + issuerdn + ")");
1217
1218        Connection JavaDoc con = null;
1219        PreparedStatement JavaDoc ps = null;
1220        ResultSet JavaDoc result = null;
1221        try {
1222            con = JDBCUtil.getDBConnection(JNDINames.DATASOURCE);
1223            ps = con.prepareStatement("select MAX(CRLNumber) from CRLData where issuerDN=?");
1224            ps.setString(1, issuerdn);
1225            result = ps.executeQuery();
1226
1227            int maxnumber = 0;
1228            if (result.next())
1229                maxnumber = result.getInt(1);
1230            debug("<getLastCRLNumber(" + maxnumber + ")");
1231
1232            return maxnumber;
1233        } catch (Exception JavaDoc e) {
1234            throw new EJBException JavaDoc(e);
1235        } finally {
1236            JDBCUtil.close(con, ps, result);
1237        }
1238    } //getLastCRLNumber
1239

1240    /**
1241     * Method used to add a CertReqHistory to database
1242     *
1243     * @param admin calling the methods
1244     * @param certificate the certificate to store (Only X509Certificate used for now)
1245     * @param useradmindata the user information used when issuing the certificate.
1246     * @ejb.transaction type="Required"
1247     * @ejb.interface-method
1248     */

1249    public void addCertReqHistoryData(Admin admin, Certificate JavaDoc certificate, UserDataVO useradmindata){
1250        X509Certificate JavaDoc cert = (X509Certificate JavaDoc) certificate;
1251        debug(">addCertReqHistData(" + cert.getSerialNumber() + ", " + cert.getIssuerDN() + ", " + useradmindata.getUsername() + ")");
1252        try {
1253            CertReqHistoryDataPK pk = new CertReqHistoryDataPK();
1254            pk.fingerprint = CertTools.getFingerprintAsString(cert);
1255            certReqHistoryHome.create(cert,useradmindata);
1256            String JavaDoc msg = intres.getLocalizedMessage("store.storehistory", useradmindata.getUsername());
1257            getLogSession().log(admin, cert, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), useradmindata.getUsername(), cert, LogEntry.EVENT_INFO_STORECERTIFICATE, msg);
1258        } catch (Exception JavaDoc e) {
1259            String JavaDoc msg = intres.getLocalizedMessage("store.errorstorehistory", useradmindata.getUsername());
1260            getLogSession().log(admin, cert, LogEntry.MODULE_CA, new java.util.Date JavaDoc(), useradmindata.getUsername(), cert, LogEntry.EVENT_ERROR_STORECERTIFICATE, msg);
1261            throw new EJBException JavaDoc(e);
1262        }
1263        debug("<addCertReqHistData()");
1264    }
1265    
1266    /**
1267     * Method to remove CertReqHistory data.
1268     * @param admin
1269     * @param certFingerprint the primary key.
1270     * @ejb.transaction type="Required"
1271     * @ejb.interface-method
1272     */

1273    public void removeCertReqHistoryData(Admin admin, String JavaDoc certFingerprint){
1274        debug(">removeCertReqHistData(" + certFingerprint + ")");
1275        try {
1276            CertReqHistoryDataPK pk = new CertReqHistoryDataPK();
1277            pk.fingerprint = certFingerprint;
1278            String JavaDoc msg = intres.getLocalizedMessage("store.removehistory", certFingerprint);
1279            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_STORECERTIFICATE, msg);
1280            this.certReqHistoryHome.remove(pk);
1281        } catch (Exception JavaDoc e) {
1282            String JavaDoc msg = intres.getLocalizedMessage("store.errorremovehistory", certFingerprint);
1283            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_STORECERTIFICATE, msg);
1284            throw new EJBException JavaDoc(e);
1285        }
1286        debug("<removeCertReqHistData()");
1287    }
1288    
1289    /**
1290     * Retrieves the certificate request data belonging to given certificate serialnumber and issuerdn
1291     *
1292     * @param admin
1293     * @param certificateSN serial number of the certificate
1294     * @param issuerDN
1295     * @return the CertReqHistory or null if no data is stored with the certificate.
1296     * @ejb.interface-method
1297     */

1298    public CertReqHistory getCertReqHistory(Admin admin, BigInteger JavaDoc certificateSN, String JavaDoc issuerDN){
1299        CertReqHistory retval = null;
1300        
1301        try{
1302          Collection JavaDoc result = certReqHistoryHome.findByIssuerDNSerialNumber(issuerDN, certificateSN.toString());
1303          if(result.iterator().hasNext())
1304            retval = ((CertReqHistoryDataLocal) result.iterator().next()).getCertReqHistory();
1305        }catch(FinderException JavaDoc fe){
1306            // Do nothing but return null
1307
}
1308        
1309        return retval;
1310    }
1311    
1312    
1313    /**
1314     * Retrieves all cert request datas belonging to a user.
1315     * @param admin
1316     * @param username
1317     * @return a collection of CertReqHistory
1318     * @ejb.interface-method
1319     */

1320    public List JavaDoc getCertReqHistory(Admin admin, String JavaDoc username){
1321        ArrayList JavaDoc retval = new ArrayList JavaDoc();
1322        
1323        try{
1324          Collection JavaDoc result = certReqHistoryHome.findByUsername(username);
1325          Iterator JavaDoc iter = result.iterator();
1326          while(iter.hasNext()){
1327            retval.add(((CertReqHistoryDataLocal) iter.next()).getCertReqHistory());
1328          }
1329        }catch(FinderException JavaDoc fe){
1330            // Do nothing but return null
1331
}
1332        
1333        return retval;
1334    }
1335    
1336    
1337    /**
1338     * Adds a certificate profile to the database.
1339     *
1340     * @param admin administrator performing the task
1341     * @param certificateprofilename readable name of new certificate profile
1342     * @param certificateprofile the profile to be added
1343     * @ejb.transaction type="Required"
1344     * @ejb.interface-method
1345     */

1346    public void addCertificateProfile(Admin admin, String JavaDoc certificateprofilename,
1347                                      CertificateProfile certificateprofile) throws CertificateProfileExistsException {
1348        addCertificateProfile(admin, findFreeCertificateProfileId(), certificateprofilename, certificateprofile);
1349    } // addCertificateProfile
1350

1351    /**
1352     * Adds a certificate profile to the database.
1353     *
1354     * @param admin administrator performing the task
1355     * @param certificateprofileid internal ID of new certificate profile, use only if you know it's right.
1356     * @param certificateprofilename readable name of new certificate profile
1357     * @param certificateprofile the profile to be added
1358     * @ejb.transaction type="Required"
1359     * @ejb.interface-method
1360     */

1361    public void addCertificateProfile(Admin admin, int certificateprofileid, String JavaDoc certificateprofilename,
1362                                      CertificateProfile certificateprofile) throws CertificateProfileExistsException {
1363        if (isCertificateProfileNameFixed(certificateprofilename)) {
1364            String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofilefixed", certificateprofilename);
1365            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1366            throw new CertificateProfileExistsException(msg);
1367        }
1368
1369        if (isFreeCertificateProfileId(certificateprofileid)) {
1370            try {
1371                certprofilehome.findByCertificateProfileName(certificateprofilename);
1372                String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofileexists", certificateprofilename);
1373                throw new CertificateProfileExistsException(msg);
1374            } catch (FinderException JavaDoc e) {
1375                try {
1376                    certprofilehome.create(new Integer JavaDoc(certificateprofileid), certificateprofilename,
1377                            certificateprofile);
1378                    String JavaDoc msg = intres.getLocalizedMessage("store.addedcertprofile", certificateprofilename);
1379                    getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CERTPROFILE, msg);
1380                } catch (Exception JavaDoc f) {
1381                    String JavaDoc msg = intres.getLocalizedMessage("store.errorcreatecertprofile", certificateprofilename);
1382                    getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1383                }
1384            }
1385        }
1386    } // addCertificateProfile
1387

1388    /**
1389     * Adds a certificateprofile with the same content as the original certificateprofile,
1390     *
1391     * @param admin Administrator performing the operation
1392     * @param originalcertificateprofilename readable name of old certificate profile
1393     * @param newcertificateprofilename readable name of new certificate profile
1394     * @ejb.transaction type="Required"
1395     * @ejb.interface-method
1396     */

1397    public void cloneCertificateProfile(Admin admin, String JavaDoc originalcertificateprofilename, String JavaDoc newcertificateprofilename) throws CertificateProfileExistsException {
1398        CertificateProfile certificateprofile = null;
1399
1400        if (isCertificateProfileNameFixed(newcertificateprofilename)) {
1401            String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofilefixed", newcertificateprofilename);
1402            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1403            throw new CertificateProfileExistsException(msg);
1404        }
1405
1406        try {
1407            certificateprofile = (CertificateProfile) getCertificateProfile(admin, originalcertificateprofilename).clone();
1408
1409            boolean issuperadministrator = false;
1410            try {
1411                issuperadministrator = getAuthorizationSession().isAuthorizedNoLog(admin, "/super_administrator");
1412            } catch (AuthorizationDeniedException ade) {
1413            }
1414
1415            if (!issuperadministrator && certificateprofile.isApplicableToAnyCA()) {
1416                // Not superadministrator, do not use ANYCA;
1417
Collection JavaDoc authcas = getAuthorizationSession().getAuthorizedCAIds(admin);
1418                certificateprofile.setAvailableCAs(authcas);
1419            }
1420
1421            try {
1422                certprofilehome.findByCertificateProfileName(newcertificateprofilename);
1423                String JavaDoc msg = intres.getLocalizedMessage("store.erroraddprofilewithtempl", newcertificateprofilename, originalcertificateprofilename);
1424                getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1425                throw new CertificateProfileExistsException();
1426            } catch (FinderException JavaDoc e) {
1427                try {
1428                    certprofilehome.create(new Integer JavaDoc(findFreeCertificateProfileId()), newcertificateprofilename, certificateprofile);
1429                    String JavaDoc msg = intres.getLocalizedMessage("store.addedprofilewithtempl", newcertificateprofilename, originalcertificateprofilename);
1430                    getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CERTPROFILE, msg);
1431                } catch (CreateException JavaDoc f) {
1432                }
1433            }
1434        } catch (CloneNotSupportedException JavaDoc f) {
1435        }
1436
1437    } // cloneCertificateProfile
1438

1439    /**
1440     * Removes a certificateprofile from the database.
1441     *
1442     * @param admin Administrator performing the operation
1443     * @ejb.transaction type="Required"
1444     * @ejb.interface-method
1445     */

1446    public void removeCertificateProfile(Admin admin, String JavaDoc certificateprofilename) {
1447        try {
1448            CertificateProfileDataLocal pdl = certprofilehome.findByCertificateProfileName(certificateprofilename);
1449            pdl.remove();
1450            String JavaDoc msg = intres.getLocalizedMessage("store.removedprofile", certificateprofilename);
1451            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CERTPROFILE, msg);
1452        } catch (Exception JavaDoc e) {
1453            String JavaDoc msg = intres.getLocalizedMessage("store.errorremoveprofile", certificateprofilename);
1454            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1455        }
1456    } // removeCertificateProfile
1457

1458    /**
1459     * Renames a certificateprofile
1460     *
1461     * @ejb.transaction type="Required"
1462     * @ejb.interface-method
1463     */

1464    public void renameCertificateProfile(Admin admin, String JavaDoc oldcertificateprofilename, String JavaDoc newcertificateprofilename) throws CertificateProfileExistsException {
1465        if (isCertificateProfileNameFixed(newcertificateprofilename)) {
1466            String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofilefixed", newcertificateprofilename);
1467            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1468            throw new CertificateProfileExistsException(msg);
1469        }
1470        if (isCertificateProfileNameFixed(oldcertificateprofilename)) {
1471            String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofilefixed", oldcertificateprofilename);
1472            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1473            throw new CertificateProfileExistsException(msg);
1474        }
1475
1476        try {
1477            certprofilehome.findByCertificateProfileName(newcertificateprofilename);
1478            String JavaDoc msg = intres.getLocalizedMessage("store.errorcertprofileexists", newcertificateprofilename);
1479            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1480            throw new CertificateProfileExistsException();
1481        } catch (FinderException JavaDoc e) {
1482            try {
1483                CertificateProfileDataLocal pdl = certprofilehome.findByCertificateProfileName(oldcertificateprofilename);
1484                pdl.setCertificateProfileName(newcertificateprofilename);
1485                String JavaDoc msg = intres.getLocalizedMessage("store.renamedprofile", oldcertificateprofilename, newcertificateprofilename);
1486                getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CERTPROFILE, msg);
1487            } catch (FinderException JavaDoc f) {
1488                String JavaDoc msg = intres.getLocalizedMessage("store.errorrenameprofile", oldcertificateprofilename, newcertificateprofilename);
1489                getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1490            }
1491        }
1492    } // renameCertificateProfile
1493

1494    /**
1495     * Updates certificateprofile data
1496     *
1497     * @param admin Administrator performing the operation
1498     * @ejb.transaction type="Required"
1499     * @ejb.interface-method
1500     */

1501    public void changeCertificateProfile(Admin admin, String JavaDoc certificateprofilename, CertificateProfile certificateprofile) {
1502        try {
1503            CertificateProfileDataLocal pdl = certprofilehome.findByCertificateProfileName(certificateprofilename);
1504            pdl.setCertificateProfile(certificateprofile);
1505            String JavaDoc msg = intres.getLocalizedMessage("store.editedprofile", certificateprofilename);
1506            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_INFO_CERTPROFILE, msg);
1507        } catch (FinderException JavaDoc e) {
1508            String JavaDoc msg = intres.getLocalizedMessage("store.erroreditprofile", certificateprofilename);
1509            getLogSession().log(admin, admin.getCaId(), LogEntry.MODULE_CA, new java.util.Date JavaDoc(), null, null, LogEntry.EVENT_ERROR_CERTPROFILE, msg);
1510        }
1511    }// changeCertificateProfile
1512

1513    /**
1514     * Retrives a Collection of id:s (Integer) to authorized profiles.
1515     *
1516     * @param certprofiletype should be either CertificateDataBean.CERTTYPE_ENDENTITY, CertificateDataBean.CERTTYPE_SUBCA, CertificateDataBean.CERTTYPE_ROOTCA,
1517     * CertificateDataBean.CERTTYPE_HARDTOKEN (i.e EndEntity certificates and Hardtoken fixed profiles) or 0 for all.
1518     * Retrives certificate profile names sorted.
1519     * @return Collection of id:s (Integer)
1520     * @ejb.interface-method
1521     */

1522    public Collection JavaDoc getAuthorizedCertificateProfileIds(Admin admin, int certprofiletype) {
1523        ArrayList JavaDoc returnval = new ArrayList JavaDoc();
1524        Collection JavaDoc result = null;
1525
1526        HashSet JavaDoc authorizedcaids = new HashSet JavaDoc(getAuthorizationSession().getAuthorizedCAIds(admin));
1527
1528        // Add fixed certificate profiles.
1529
if (certprofiletype == 0 || certprofiletype == CertificateDataBean.CERTTYPE_ENDENTITY || certprofiletype == CertificateDataBean.CERTTYPE_HARDTOKEN){
1530            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_ENDUSER));
1531            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_OCSPSIGNER));
1532        }
1533        if (certprofiletype == 0 || certprofiletype == CertificateDataBean.CERTTYPE_SUBCA)
1534            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_SUBCA));
1535        if (certprofiletype == 0 || certprofiletype == CertificateDataBean.CERTTYPE_ROOTCA)
1536            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_ROOTCA));
1537
1538        if (certprofiletype == 0 || certprofiletype == CertificateDataBean.CERTTYPE_HARDTOKEN) {
1539            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENAUTH));
1540            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENAUTHENC));
1541            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENENC));
1542            returnval.add(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENSIGN));
1543        }
1544
1545        try {
1546            result = certprofilehome.findAll();
1547            Iterator JavaDoc i = result.iterator();
1548            while (i.hasNext()) {
1549                CertificateProfileDataLocal next = (CertificateProfileDataLocal) i.next();
1550                CertificateProfile profile = next.getCertificateProfile();
1551                // Check if all profiles available CAs exists in authorizedcaids.
1552
if (certprofiletype == 0 || certprofiletype == profile.getType()
1553                        || (profile.getType() == CertificateDataBean.CERTTYPE_ENDENTITY &&
1554                        certprofiletype == CertificateDataBean.CERTTYPE_HARDTOKEN)) {
1555                    Iterator JavaDoc availablecas = profile.getAvailableCAs().iterator();
1556                    boolean allexists = true;
1557                    while (availablecas.hasNext()) {
1558                        Integer JavaDoc nextcaid = (Integer JavaDoc) availablecas.next();
1559                        if (nextcaid.intValue() == CertificateProfile.ANYCA) {
1560                            allexists = true;
1561                            break;
1562                        }
1563
1564                        if (!authorizedcaids.contains(nextcaid)) {
1565                            allexists = false;
1566                            break;
1567                        }
1568                    }
1569
1570                    if (allexists)
1571                        returnval.add(next.getId());
1572                }
1573            }
1574        } catch (FinderException JavaDoc e) {
1575        }
1576        return returnval;
1577    } // getAuthorizedCertificateProfileNames
1578

1579
1580    /**
1581     * Method creating a hashmap mapping profile id (Integer) to profile name (String).
1582     *
1583     * @param admin Administrator performing the operation
1584     * @ejb.interface-method
1585     */

1586    public HashMap JavaDoc getCertificateProfileIdToNameMap(Admin admin) {
1587        HashMap JavaDoc returnval = new HashMap JavaDoc();
1588        Collection JavaDoc result = null;
1589        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_ENDUSER),
1590                EndUserCertificateProfile.CERTIFICATEPROFILENAME);
1591        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_SUBCA),
1592                CACertificateProfile.CERTIFICATEPROFILENAME);
1593        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_ROOTCA),
1594                RootCACertificateProfile.CERTIFICATEPROFILENAME);
1595        
1596        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_OCSPSIGNER),
1597                OCSPSignerCertificateProfile.CERTIFICATEPROFILENAME);
1598
1599        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENAUTH),
1600                HardTokenAuthCertificateProfile.CERTIFICATEPROFILENAME);
1601        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENAUTHENC),
1602                HardTokenAuthEncCertificateProfile.CERTIFICATEPROFILENAME);
1603        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENENC),
1604                HardTokenEncCertificateProfile.CERTIFICATEPROFILENAME);
1605        returnval.put(new Integer JavaDoc(SecConst.CERTPROFILE_FIXED_HARDTOKENSIGN),
1606                HardTokenSignCertificateProfile.CERTIFICATEPROFILENAME);
1607
1608
1609        try {
1610            result = certprofilehome.findAll();
1611            Iterator JavaDoc i = result.iterator();
1612            while (i.hasNext()) {
1613                CertificateProfileDataLocal next = (CertificateProfileDataLocal) i.next();
1614                returnval.put(next.getId(), next.getCertificateProfileName());
1615            }
1616        } catch (FinderException JavaDoc e) {
1617        }
1618        return returnval;
1619    } // getCertificateProfileIdToNameMap
1620

1621
1622    /**
1623     * Retrives a named certificate profile.
1624     *
1625     * @ejb.interface-method
1626     */

1627    public CertificateProfile getCertificateProfile(Admin admin, String JavaDoc certificateprofilename) {
1628        CertificateProfile returnval = null;
1629
1630        if (certificateprofilename.equals(EndUserCertificateProfile.CERTIFICATEPROFILENAME))
1631            return new EndUserCertificateProfile();
1632
1633        if (certificateprofilename.equals(CACertificateProfile.CERTIFICATEPROFILENAME))
1634            return new CACertificateProfile();
1635
1636        if (certificateprofilename.equals(OCSPSignerCertificateProfile.CERTIFICATEPROFILENAME))
1637            return new OCSPSignerCertificateProfile();
1638        
1639        if (certificateprofilename.equals(RootCACertificateProfile.CERTIFICATEPROFILENAME))
1640            return new RootCACertificateProfile();
1641
1642        if (certificateprofilename.equals(HardTokenAuthCertificateProfile.CERTIFICATEPROFILENAME))
1643            return new HardTokenAuthCertificateProfile();
1644
1645        if (certificateprofilename.equals(HardTokenAuthEncCertificateProfile.CERTIFICATEPROFILENAME))
1646            return new HardTokenAuthEncCertificateProfile();
1647
1648        if (certificateprofilename.equals(HardTokenEncCertificateProfile.CERTIFICATEPROFILENAME))
1649            return new HardTokenEncCertificateProfile();
1650
1651        if (certificateprofilename.equals(HardTokenSignCertificateProfile.CERTIFICATEPROFILENAME))
1652            return new HardTokenSignCertificateProfile();
1653
1654
1655        try {
1656            returnval = (certprofilehome.findByCertificateProfileName(certificateprofilename)).getCertificateProfile();
1657        } catch (FinderException JavaDoc e) {
1658            // return null if we cant find it
1659
}
1660        return returnval;
1661    } // getCertificateProfile
1662

1663    /**
1664     * Finds a certificate profile by id.
1665     *
1666     * @param admin Administrator performing the operation
1667     * @ejb.interface-method
1668     */

1669    public CertificateProfile getCertificateProfile(Admin admin, int id) {
1670        CertificateProfile returnval = null;
1671
1672        if (id < SecConst.FIXED_CERTIFICATEPROFILE_BOUNDRY) {
1673            switch (id) {
1674                case SecConst.CERTPROFILE_FIXED_ENDUSER:
1675                    returnval = new EndUserCertificateProfile();
1676                    break;
1677                case SecConst.CERTPROFILE_FIXED_SUBCA:
1678                    returnval = new CACertificateProfile();
1679                    break;
1680                case SecConst.CERTPROFILE_FIXED_ROOTCA:
1681                    returnval = new RootCACertificateProfile();
1682                    break;
1683                case SecConst.CERTPROFILE_FIXED_HARDTOKENAUTH:
1684                    returnval = new HardTokenAuthCertificateProfile();
1685                    break;
1686                case SecConst.CERTPROFILE_FIXED_HARDTOKENAUTHENC:
1687                    returnval = new HardTokenAuthEncCertificateProfile();
1688                    break;
1689                case SecConst.CERTPROFILE_FIXED_HARDTOKENENC:
1690                    returnval = new HardTokenEncCertificateProfile();
1691                    break;
1692                case SecConst.CERTPROFILE_FIXED_HARDTOKENSIGN:
1693                    returnval = new HardTokenSignCertificateProfile();
1694                    break;
1695                default:
1696                    returnval = new EndUserCertificateProfile();
1697            }
1698        } else {
1699            try {
1700                returnval = (certprofilehome.findByPrimaryKey(new Integer JavaDoc(id))).getCertificateProfile();
1701            } catch (FinderException JavaDoc e) {
1702                // return null if we cant find it
1703
}
1704        }
1705        return returnval;
1706    } // getCertificateProfile
1707

1708
1709    /**
1710     * Returns a certificate profile id, given it's certificate profile name
1711     *
1712     * @param admin Administrator performing the operation
1713     * @return the id or 0 if certificateprofile cannot be found.
1714     * @ejb.interface-method
1715     */

1716    public int getCertificateProfileId(Admin admin, String JavaDoc certificateprofilename) {
1717        int returnval = 0;
1718
1719        if (certificateprofilename.equals(EndUserCertificateProfile.CERTIFICATEPROFILENAME))
1720            return SecConst.CERTPROFILE_FIXED_ENDUSER;
1721
1722        if (certificateprofilename.equals(CACertificateProfile.CERTIFICATEPROFILENAME))
1723            return SecConst.CERTPROFILE_FIXED_SUBCA;
1724
1725        if (certificateprofilename.equals(RootCACertificateProfile.CERTIFICATEPROFILENAME))
1726            return SecConst.CERTPROFILE_FIXED_ROOTCA;
1727
1728        if (certificateprofilename.equals(HardTokenAuthCertificateProfile.CERTIFICATEPROFILENAME))
1729            return SecConst.CERTPROFILE_FIXED_HARDTOKENAUTH;
1730
1731        if (certificateprofilename.equals(HardTokenAuthEncCertificateProfile.CERTIFICATEPROFILENAME))
1732            return SecConst.CERTPROFILE_FIXED_HARDTOKENAUTHENC;
1733
1734        if (certificateprofilename.equals(HardTokenEncCertificateProfile.CERTIFICATEPROFILENAME))
1735            return SecConst.CERTPROFILE_FIXED_HARDTOKENENC;
1736
1737        if (certificateprofilename.equals(HardTokenSignCertificateProfile.CERTIFICATEPROFILENAME))
1738            return SecConst.CERTPROFILE_FIXED_HARDTOKENSIGN;
1739
1740        try {
1741            Integer JavaDoc id = (certprofilehome.findByCertificateProfileName(certificateprofilename)).getId();
1742            returnval = id.intValue();
1743        } catch (FinderException JavaDoc e) {
1744        }
1745
1746        return returnval;
1747    } // getCertificateProfileId
1748

1749    /**
1750     * Returns a certificateprofiles name given it's id.
1751     *
1752     * @param admin Administrator performing the operation
1753     * @return certificateprofilename or null if certificateprofile id doesn't exists.
1754     * @ejb.interface-method
1755     */

1756    public String JavaDoc getCertificateProfileName(Admin admin, int id) {
1757        String JavaDoc returnval = null;
1758
1759        // Is id a fixed profile
1760
if (id < SecConst.FIXED_CERTIFICATEPROFILE_BOUNDRY) {
1761            switch (id) {
1762                case SecConst.CERTPROFILE_FIXED_ENDUSER:
1763                    returnval = EndUserCertificateProfile.CERTIFICATEPROFILENAME;
1764                    break;
1765                case SecConst.CERTPROFILE_FIXED_SUBCA:
1766                    returnval = CACertificateProfile.CERTIFICATEPROFILENAME;
1767                    break;
1768                case SecConst.CERTPROFILE_FIXED_ROOTCA:
1769                    returnval = RootCACertificateProfile.CERTIFICATEPROFILENAME;
1770                    break;
1771                case SecConst.CERTPROFILE_FIXED_OCSPSIGNER:
1772                    returnval = OCSPSignerCertificateProfile.CERTIFICATEPROFILENAME;
1773                    break;
1774                case SecConst.CERTPROFILE_FIXED_HARDTOKENAUTH:
1775                    returnval = HardTokenAuthCertificateProfile.CERTIFICATEPROFILENAME;
1776                    break;
1777                case SecConst.CERTPROFILE_FIXED_HARDTOKENAUTHENC:
1778                    returnval = HardTokenAuthEncCertificateProfile.CERTIFICATEPROFILENAME;
1779                    break;
1780                case SecConst.CERTPROFILE_FIXED_HARDTOKENENC:
1781                    returnval = HardTokenEncCertificateProfile.CERTIFICATEPROFILENAME;
1782                    break;
1783                case SecConst.CERTPROFILE_FIXED_HARDTOKENSIGN:
1784                    returnval = HardTokenSignCertificateProfile.CERTIFICATEPROFILENAME;
1785                    break;
1786                default:
1787                    returnval = EndUserCertificateProfile.CERTIFICATEPROFILENAME;
1788
1789
1790            }
1791        } else {
1792            try {
1793                returnval = (certprofilehome.findByPrimaryKey(new Integer JavaDoc(id))).getCertificateProfileName();
1794            } catch (FinderException JavaDoc e) {
1795            }
1796        }
1797
1798        return returnval;
1799
1800    } // getCertificateProfileName
1801

1802    /**
1803     * Method to check if a CA exists in any of the certificate profiles. Used to avoid desyncronization of CA data.
1804     *
1805     * @param admin Administrator performing the operation
1806     * @param caid the caid to search for.
1807     * @return true if ca exists in any of the certificate profiles.
1808     * @ejb.interface-method
1809     */

1810    public boolean existsCAInCertificateProfiles(Admin admin, int caid) {
1811        Iterator JavaDoc availablecas = null;
1812        boolean exists = false;
1813        try {
1814            Collection JavaDoc result = certprofilehome.findAll();
1815            Iterator JavaDoc i = result.iterator();
1816            while (i.hasNext() && !exists) {
1817                CertificateProfile certProfile = ((CertificateProfileDataLocal) i.next()).getCertificateProfile();
1818                if(certProfile.getType() == CertificateProfile.TYPE_ENDENTITY){
1819                    availablecas = certProfile.getAvailableCAs().iterator();
1820                    while (availablecas.hasNext()) {
1821                        if (((Integer JavaDoc) availablecas.next()).intValue() == caid ) {
1822                            exists = true;
1823                            break;
1824                        }
1825                    }
1826                }
1827            }
1828        } catch (FinderException JavaDoc e) {
1829        }
1830
1831        return exists;
1832    } // existsCAInCertificateProfiles
1833

1834    /**
1835     * Method to check if a Publisher exists in any of the certificate profiles. Used to avoid desyncronization of publisher data.
1836     *
1837     * @param publisherid the publisherid to search for.
1838     * @return true if publisher exists in any of the certificate profiles.
1839     * @ejb.interface-method
1840     */

1841    public boolean existsPublisherInCertificateProfiles(Admin admin, int publisherid) {
1842        Iterator JavaDoc availablepublishers = null;
1843        boolean exists = false;
1844        try {
1845            Collection JavaDoc result = certprofilehome.findAll();
1846            Iterator JavaDoc i = result.iterator();
1847            while (i.hasNext() && !exists) {
1848                availablepublishers = ((CertificateProfileDataLocal) i.next()).getCertificateProfile().getPublisherList().iterator();
1849                while (availablepublishers.hasNext()) {
1850                    if (((Integer JavaDoc) availablepublishers.next()).intValue() == publisherid) {
1851                        exists = true;
1852                        break;
1853                    }
1854                }
1855            }
1856        } catch (FinderException JavaDoc e) {
1857        }
1858
1859        return exists;
1860    } // existsPublisherInCertificateProfiles
1861

1862    // Private methods
1863

1864    private int findFreeCertificateProfileId() {
1865        Random JavaDoc random = new Random JavaDoc((new Date JavaDoc()).getTime());
1866        int id = random.nextInt();
1867        boolean foundfree = false;
1868
1869        while (!foundfree) {
1870            try {
1871                if (id > SecConst.FIXED_CERTIFICATEPROFILE_BOUNDRY) {
1872                    certprofilehome.findByPrimaryKey(new Integer JavaDoc(id));
1873                } else {
1874                    id = random.nextInt();
1875                }
1876            } catch (FinderException JavaDoc e) {
1877                foundfree = true;
1878            }
1879        }
1880        return id;
1881    } // findFreeCertificateProfileId
1882

1883    
1884    private boolean isCertificateProfileNameFixed(String JavaDoc certificateprofilename) {
1885        boolean returnval = false;
1886
1887        if (certificateprofilename.equals(EndUserCertificateProfile.CERTIFICATEPROFILENAME))
1888            return true;
1889
1890        if (certificateprofilename.equals(CACertificateProfile.CERTIFICATEPROFILENAME))
1891            return true;
1892
1893        if (certificateprofilename.equals(RootCACertificateProfile.CERTIFICATEPROFILENAME))
1894            return true;
1895
1896        return returnval;
1897    }
1898
1899    private boolean isFreeCertificateProfileId(int id) {
1900        boolean foundfree = false;
1901        try {
1902            if (id > SecConst.FIXED_CERTIFICATEPROFILE_BOUNDRY) {
1903                certprofilehome.findByPrimaryKey(new Integer JavaDoc(id));
1904            }
1905        } catch (FinderException JavaDoc e) {
1906            foundfree = true;
1907        }
1908        return foundfree;
1909    } // isFreeCertificateProfileId
1910

1911    private class MyAdapter implements CertificateDataUtil.Adapter {
1912        /* (non-Javadoc)
1913         * @see org.ejbca.core.ejb.ca.store.CertificateDataUtil.Adapter#getLogger()
1914         */

1915        public Logger getLogger() {
1916            return log;
1917        }
1918        /* (non-Javadoc)
1919         * @see org.ejbca.core.ejb.ca.store.CertificateDataUtil.Adapter#log(org.ejbca.core.model.log.Admin, int, int, java.util.Date, java.lang.String, java.security.cert.X509Certificate, int, java.lang.String)
1920         */

1921        public void log(Admin admin, int caid, int module, Date JavaDoc time, String JavaDoc username,
1922                        X509Certificate JavaDoc certificate, int event, String JavaDoc comment) {
1923            getLogSession().log(admin, caid, module, new java.util.Date JavaDoc(),
1924                                username, certificate, event, comment);
1925        }
1926        /* (non-Javadoc)
1927         * @see org.ejbca.core.ejb.ca.store.CertificateDataUtil.Adapter#debug(java.lang.String)
1928         */

1929        public void debug(String JavaDoc s) {
1930            LocalCertificateStoreSessionBean.this.debug(s);
1931        }
1932        /* (non-Javadoc)
1933         * @see org.ejbca.core.ejb.ca.store.CertificateDataUtil.Adapter#error(java.lang.String)
1934         */

1935        public void error(String JavaDoc s) {
1936            LocalCertificateStoreSessionBean.this.error(s);
1937        }
1938        /* (non-Javadoc)
1939         * @see org.ejbca.core.ejb.ca.store.CertificateDataUtil.Adapter#error(java.lang.String)
1940         */

1941        public void error(String JavaDoc s, Exception JavaDoc e) {
1942            LocalCertificateStoreSessionBean.this.error(s, e);
1943        }
1944    }
1945} // CertificateStoreSessionBean
1946
Popular Tags