KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > cli > batch > BatchMakeP12


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.ui.cli.batch;
15
16 import java.io.File JavaDoc;
17 import java.io.FileOutputStream JavaDoc;
18 import java.io.IOException JavaDoc;
19 import java.rmi.RemoteException JavaDoc;
20 import java.security.GeneralSecurityException JavaDoc;
21 import java.security.KeyPair JavaDoc;
22 import java.security.KeyStore JavaDoc;
23 import java.security.KeyStoreException JavaDoc;
24 import java.security.NoSuchAlgorithmException JavaDoc;
25 import java.security.NoSuchProviderException JavaDoc;
26 import java.security.UnrecoverableKeyException JavaDoc;
27 import java.security.cert.Certificate JavaDoc;
28 import java.security.cert.CertificateException JavaDoc;
29 import java.security.cert.X509Certificate JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Iterator JavaDoc;
33
34 import javax.ejb.CreateException JavaDoc;
35 import javax.naming.Context JavaDoc;
36 import javax.naming.NamingException JavaDoc;
37
38 import org.apache.log4j.Logger;
39 import org.ejbca.core.ejb.InitialContextBuilder;
40 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionHome;
41 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionRemote;
42 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
43 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
44 import org.ejbca.core.ejb.ca.sign.ISignSessionHome;
45 import org.ejbca.core.ejb.ca.sign.ISignSessionRemote;
46 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionHome;
47 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionRemote;
48 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
49 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
50 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
51 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
52 import org.ejbca.core.model.InternalResources;
53 import org.ejbca.core.model.SecConst;
54 import org.ejbca.core.model.ca.catoken.CATokenConstants;
55 import org.ejbca.core.model.keyrecovery.KeyRecoveryData;
56 import org.ejbca.core.model.log.Admin;
57 import org.ejbca.core.model.ra.UserAdminConstants;
58 import org.ejbca.core.model.ra.UserDataConstants;
59 import org.ejbca.core.model.ra.UserDataVO;
60 import org.ejbca.util.CertTools;
61 import org.ejbca.util.KeyTools;
62 import org.ejbca.util.P12toPEM;
63
64
65
66
67 /**
68  * This class generates keys and request certificates for all users with status NEW. The result is
69  * generated PKCS12-files.
70  *
71  * @version $Id: BatchMakeP12.java,v 1.11 2007/01/16 11:44:29 anatom Exp $
72  */

73 public class BatchMakeP12 {
74     /**
75      * For logging
76      */

77     private static final Logger log = Logger.getLogger(BatchMakeP12.class);
78     /** Internal localization of logs and errors */
79     private static final InternalResources intres = InternalResources.getInstance();
80
81     BatchToolProperties props = new BatchToolProperties();
82
83     
84     /**
85      * Where created P12-files are stored, default username.p12
86      */

87     private String JavaDoc mainStoreDir = "";
88     private IUserAdminSessionHome adminhome;
89     private IRaAdminSessionHome raadminhome;
90     private ISignSessionHome signhome;
91     private ICAAdminSessionHome caadminhome;
92     private IKeyRecoverySessionHome keyrecoveryhome;
93     private IAuthenticationSessionHome authhome;
94     private Admin administrator;
95     private boolean usekeyrecovery = false;
96
97     /**
98      * Gets an initial context
99      *
100      * @return new initial context
101      * @throws NamingException if we can't find jndi name
102      */

103     public static Context JavaDoc getInitialContext() throws NamingException JavaDoc {
104         log.debug(">GetInitialContext");
105
106         // jndi.properties must exist in classpath
107
Context JavaDoc ctx = InitialContextBuilder.getInstance().getInitialContext();
108         log.debug("<GetInitialContext");
109
110         return ctx;
111     }
112
113     /**
114      * Creates new BatchMakeP12 object.
115      *
116      * @throws javax.naming.NamingException
117      * @throws CreateException
118      * @throws RemoteException
119      */

120     public BatchMakeP12()
121             throws javax.naming.NamingException JavaDoc, javax.ejb.CreateException JavaDoc, java.rmi.RemoteException JavaDoc,
122             java.io.IOException JavaDoc {
123         log.debug(">BatchMakeP12:");
124         
125         administrator = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
126
127
128         // Bouncy Castle security provider
129
CertTools.installBCProvider();
130
131         Context JavaDoc jndiContext = getInitialContext();
132         Object JavaDoc obj = jndiContext.lookup("UserAdminSession");
133         adminhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class);
134         obj = jndiContext.lookup("RaAdminSession");
135         raadminhome = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IRaAdminSessionHome.class);
136         obj = jndiContext.lookup("RSASignSession");
137         signhome = (ISignSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ISignSessionHome.class);
138         obj = jndiContext.lookup("CAAdminSession");
139         caadminhome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICAAdminSessionHome.class);
140         obj = jndiContext.lookup("AuthenticationSession");
141         authhome = (IAuthenticationSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IAuthenticationSessionHome.class);
142         
143         IRaAdminSessionRemote raadmin = raadminhome.create();
144         usekeyrecovery = (raadmin.loadGlobalConfiguration(administrator)).getEnableKeyRecovery();
145
146         if (usekeyrecovery) {
147             obj = jndiContext.lookup("KeyRecoverySession");
148             keyrecoveryhome = (IKeyRecoverySessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IKeyRecoverySessionHome.class);
149         }
150
151
152         log.debug("<BatchMakeP12:");
153     } // BatchMakeP12
154

155     /**
156      * Gets full CA-certificate chain.
157      *
158      * @return Certificate[]
159      */

160     private Certificate JavaDoc[] getCACertChain(int caid)
161             throws Exception JavaDoc {
162         log.debug(">getCACertChain()");
163
164         ISignSessionRemote ss = signhome.create();
165         Certificate JavaDoc[] chain = (Certificate JavaDoc[]) ss.getCertificateChain(administrator, caid).toArray(new Certificate JavaDoc[0]);
166         log.debug("<getCACertChain()");
167
168         return chain;
169     } // getCACertificate
170

171     /**
172      * Sets the location where generated P12-files will be stored, full name will be:
173      * mainStoreDir/username.p12.
174      *
175      * @param dir existing directory
176      */

177     public void setMainStoreDir(String JavaDoc dir) {
178         mainStoreDir = dir;
179     }
180
181     /**
182      * Stores keystore.
183      *
184      * @param ks KeyStore
185      * @param username username, the owner of the keystore
186      * @param kspassword the password used to protect the peystore
187      * @param createJKS if a jks should be created
188      * @param createPEM if pem files should be created
189      * @throws IOException if directory to store keystore cannot be created
190      */

191     private void storeKeyStore(KeyStore JavaDoc ks, String JavaDoc username, String JavaDoc kspassword, boolean createJKS,
192                                boolean createPEM)
193             throws IOException JavaDoc, KeyStoreException JavaDoc, UnrecoverableKeyException JavaDoc, NoSuchAlgorithmException JavaDoc,
194             NoSuchProviderException JavaDoc, CertificateException JavaDoc {
195         log.debug(">storeKeyStore: ks=" + ks.toString() + ", username=" + username);
196
197         // Where to store it?
198
if (mainStoreDir == null) {
199             throw new IOException JavaDoc("Can't find directory to store keystore in.");
200         }
201
202         String JavaDoc keyStoreFilename = mainStoreDir + "/" + username;
203
204         if (createJKS) {
205             keyStoreFilename += ".jks";
206         } else {
207             keyStoreFilename += ".p12";
208         }
209
210         // If we should also create PEM-files, do that
211
if (createPEM) {
212             String JavaDoc PEMfilename = mainStoreDir + "/pem";
213             P12toPEM p12topem = new P12toPEM(ks, kspassword, true);
214             p12topem.setExportPath(PEMfilename);
215             p12topem.createPEM();
216         } else {
217             FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(keyStoreFilename);
218             ks.store(os, kspassword.toCharArray());
219         }
220
221         log.debug("Keystore stored in " + keyStoreFilename);
222         log.debug("<storeKeyStore: ks=" + ks.toString() + ", username=" + username);
223     } // storeKeyStore
224

225     /**
226      * Creates files for a user, sends request to CA, receives reply and creates P12.
227      *
228      * @param username username
229      * @param password user's password
230      * @param id of CA used to issue the keystore certificates
231      * @param rsaKeys a previously generated RSA keypair
232      * @param createJKS if a jks should be created
233      * @param createPEM if pem files should be created
234      * @param savekeys if generated keys should be saved in db (key recovery)
235      * @param orgCert if an original key recovered cert should be reused, null indicates generate new cert.
236      * @throws Exception if the certificate is not an X509 certificate
237      * @throws Exception if the CA-certificate is corrupt
238      * @throws Exception if verification of certificate or CA-cert fails
239      * @throws Exception if keyfile (generated by ourselves) is corrupt
240      */

241
242     private void createUser(String JavaDoc username, String JavaDoc password, int caid, KeyPair JavaDoc rsaKeys, boolean createJKS, boolean createPEM, boolean savekeys, X509Certificate JavaDoc orgCert)
243             throws Exception JavaDoc {
244         log.debug(">createUser: username=" + username);
245
246         // Send the certificate request to the CA
247
ISignSessionRemote ss = signhome.create();
248         
249         X509Certificate JavaDoc cert = null;
250         
251         if(orgCert != null){
252           cert = orgCert;
253           ICAAdminSessionRemote caadminsession = caadminhome.create();
254           boolean finishUser = caadminsession.getCAInfo(administrator,caid).getFinishUser();
255           if(finishUser){
256               IAuthenticationSessionRemote authsession = authhome.create();
257               authsession.finishUser(administrator, username, password);
258           }
259           
260           
261         }else{
262             // Create self signed certificate, because ECDSA keys are not serializable
263
String JavaDoc sigAlg = CATokenConstants.SIGALG_SHA1_WITH_RSA;
264             if (props.getKeyAlg().equals("ECDSA")) {
265                 sigAlg = CATokenConstants.SIGALG_SHA256_WITH_ECDSA;
266             }
267             X509Certificate JavaDoc selfcert = CertTools.genSelfCert("CN=selfsigned", 1, null, rsaKeys.getPrivate(), rsaKeys.getPublic(), sigAlg, false);
268             cert = (X509Certificate JavaDoc) ss.createCertificate(administrator, username,
269                     password, selfcert);
270         }
271
272         //System.out.println("issuer " + CertTools.getIssuerDN(cert) + ", " + cert.getClass().getName());
273
// Make a certificate chain from the certificate and the CA-certificate
274
Certificate JavaDoc[] cachain = getCACertChain(caid);
275         // Verify CA-certificate
276
if (CertTools.isSelfSigned((X509Certificate JavaDoc) cachain[cachain.length - 1])) {
277             try {
278                 cachain[cachain.length - 1].verify(cachain[cachain.length - 1].getPublicKey());
279             } catch (GeneralSecurityException JavaDoc se) {
280                 String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorrootnotverify");
281                 throw new Exception JavaDoc(errMsg);
282             }
283         } else {
284             String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorrootnotselfsigned");
285             throw new Exception JavaDoc(errMsg);
286         }
287
288         // Verify that the user-certificate is signed by our CA
289
try {
290             cert.verify(cachain[0].getPublicKey());
291         } catch (GeneralSecurityException JavaDoc se) {
292             String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorgennotverify");
293             throw new Exception JavaDoc(errMsg);
294         }
295
296         if (usekeyrecovery && savekeys ) {
297             // Save generated keys to database.
298
IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome.create();
299             keyrecoverysession.addKeyRecoveryData(administrator, cert, username, rsaKeys);
300         }
301
302         // Use CN if as alias in the keystore, if CN is not present use username
303
String JavaDoc alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
304         if (alias == null) alias = username;
305
306         // Store keys and certificates in keystore.
307
KeyStore JavaDoc ks = null;
308
309         if (createJKS) {
310             ks = KeyTools.createJKS(alias, rsaKeys.getPrivate(), password, cert, cachain);
311         } else {
312             ks = KeyTools.createP12(alias, rsaKeys.getPrivate(), cert, cachain);
313         }
314
315         storeKeyStore(ks, username, password, createJKS, createPEM);
316         String JavaDoc iMsg = intres.getLocalizedMessage("batch.createkeystore", username);
317         log.info(iMsg);
318         log.debug("<createUser: username=" + username);
319     } // createUser
320

321     /**
322      * Does the deed with one user...
323      *
324      * @param data user data for user
325      * @param createJKS if a jks should be created
326      * @param createPEM if pem files should be created
327      * @param keyrecoverflag if we should try to revoer already existing keys
328      * @throws Exception If something goes wrong...
329      */

330     private void processUser(UserDataVO data, boolean createJKS, boolean createPEM,
331                              boolean keyrecoverflag) throws Exception JavaDoc {
332         KeyPair JavaDoc rsaKeys = null;
333         X509Certificate JavaDoc orgCert = null;
334         
335         
336         if (usekeyrecovery && keyrecoverflag) {
337             
338             IRaAdminSessionRemote raadmin = raadminhome.create();
339             boolean reusecertificate = raadmin.getEndEntityProfile(administrator, data.getEndEntityProfileId()).getReUseKeyRevoceredCertificate();
340             
341             // Recover Keys
342
IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome.create();
343             KeyRecoveryData recoveryData = keyrecoverysession.keyRecovery(administrator, data.getUsername(), data.getEndEntityProfileId());
344             if(reusecertificate){
345                 keyrecoverysession.unmarkUser(administrator,data.getUsername());
346             }
347             if (recoveryData != null) {
348                 rsaKeys = recoveryData.getKeyPair();
349                 if(reusecertificate){
350                     orgCert = (X509Certificate JavaDoc) recoveryData.getCertificate();
351                 }
352             } else {
353                 String JavaDoc errMsg = intres.getLocalizedMessage("batch.errornokeyrecoverydata", data.getUsername());
354                 throw new Exception JavaDoc(errMsg);
355             }
356         } else {
357             rsaKeys = KeyTools.genKeys(props.getKeySpec(), props.getKeyAlg());
358         }
359         // Get certificate for user and create P12
360
if (rsaKeys != null) {
361             createUser(data.getUsername(), data.getPassword(), data.getCAId(), rsaKeys, createJKS, createPEM, !keyrecoverflag && data.getKeyRecoverable(), orgCert);
362         }
363     } //processUser
364

365     private boolean doCreate(IUserAdminSessionRemote admin, UserDataVO data, int status) throws Exception JavaDoc {
366         boolean ret = false;
367         int tokentype = SecConst.TOKEN_SOFT_BROWSERGEN;
368         boolean createJKS = false;
369         boolean createPEM = false;
370         boolean createP12 = false;
371         // get users Token Type.
372
tokentype = data.getTokenType();
373         createP12 = tokentype == SecConst.TOKEN_SOFT_P12;
374         createPEM = tokentype == SecConst.TOKEN_SOFT_PEM;
375         createJKS = tokentype == SecConst.TOKEN_SOFT_JKS;
376         
377         // Only generate supported tokens
378
if (createP12 || createPEM || createJKS) {
379             if (status == UserDataConstants.STATUS_KEYRECOVERY) {
380                 String JavaDoc iMsg = intres.getLocalizedMessage("batch.retrieveingkeys", data.getUsername());
381                 log.info(iMsg);
382             } else {
383                 String JavaDoc iMsg = intres.getLocalizedMessage("batch.generatingkeys", data.getUsername());
384                 log.info(iMsg);
385             }
386             
387             // Grab new user, set status to INPROCESS
388
admin.setUserStatus(administrator, data.getUsername(),
389                     UserDataConstants.STATUS_INPROCESS);
390             processUser(data, createJKS, createPEM,
391                     (status == UserDataConstants.STATUS_KEYRECOVERY));
392             
393             // If all was OK , set status to GENERATED
394
admin.setUserStatus(administrator, data.getUsername(),
395                     UserDataConstants.STATUS_GENERATED);
396             
397             // Delete clear text password
398
admin.setClearTextPassword(administrator, data.getUsername(), null);
399             ret = true;
400             String JavaDoc iMsg = intres.getLocalizedMessage("batch.generateduser", data.getUsername());
401             log.info(iMsg);
402         } else {
403             log.debug("Cannot batchmake browser generated token for user (wrong tokentype)- " + data.getUsername());
404         }
405         return ret;
406     }
407     
408     /**
409      * Creates P12-files for all users with status NEW in the local database.
410      *
411      * @throws Exception if something goes wrong...
412      */

413     public void createAllNew() throws Exception JavaDoc {
414         log.debug(">createAllNew:");
415         String JavaDoc iMsg = intres.getLocalizedMessage("batch.generatingallstatus", "NEW");
416         log.info(iMsg);
417         createAllWithStatus(UserDataConstants.STATUS_NEW);
418         log.debug("<createAllNew:");
419     } // createAllNew
420

421     /**
422      * Creates P12-files for all users with status FAILED in the local database.
423      *
424      * @throws Exception if something goes wrong...
425      */

426     public void createAllFailed() throws Exception JavaDoc {
427         log.debug(">createAllFailed:");
428         String JavaDoc iMsg = intres.getLocalizedMessage("batch.generatingallstatus", "FAILED");
429         log.info(iMsg);
430         createAllWithStatus(UserDataConstants.STATUS_FAILED);
431         log.debug("<createAllFailed:");
432     } // createAllFailed
433

434     /**
435      * Creates P12-files for all users with status KEYRECOVER in the local database.
436      *
437      * @throws Exception if something goes wrong...
438      */

439     public void createAllKeyRecover() throws Exception JavaDoc {
440         if (usekeyrecovery) {
441             log.debug(">createAllKeyRecover:");
442             String JavaDoc iMsg = intres.getLocalizedMessage("batch.generatingallstatus", "KEYRECOVER");
443             log.info(iMsg);
444             createAllWithStatus(UserDataConstants.STATUS_KEYRECOVERY);
445             log.debug("<createAllKeyRecover:");
446         }
447     } // createAllKeyRecover
448

449     /**
450      * Creates P12-files for all users with status in the local database.
451      *
452      * @param status
453      * @throws Exception if something goes wrong...
454      */

455     public void createAllWithStatus(int status) throws Exception JavaDoc {
456         log.debug(">createAllWithStatus: " + status);
457
458         ArrayList JavaDoc result;
459         IUserAdminSessionRemote admin = adminhome.create();
460         boolean stopnow = false;
461
462         //Collection result = admin.findAllUsersByStatus(administrator, status);
463
do {
464         
465             Collection JavaDoc queryResult = admin.findAllUsersByStatusWithLimit(administrator, status, true);
466             result = new ArrayList JavaDoc();
467             
468             Iterator JavaDoc iter = queryResult.iterator();
469             while(iter.hasNext()){
470                 UserDataVO data = (UserDataVO) iter.next();
471                 if(data.getTokenType() == SecConst.TOKEN_SOFT_JKS ||
472                    data.getTokenType() == SecConst.TOKEN_SOFT_PEM ||
473                    data.getTokenType() == SecConst.TOKEN_SOFT_P12 ){
474                    result.add(data);
475                 }
476             }
477             
478             String JavaDoc iMsg = intres.getLocalizedMessage("batch.generatingnoofusers", new Integer JavaDoc(result.size()));
479             log.info(iMsg);
480
481             int failcount = 0;
482             int successcount = 0;
483
484             if (result.size() > 0) {
485                 if (result.size() < UserAdminConstants.MAXIMUM_QUERY_ROWCOUNT) {
486                     stopnow = true;
487                 }
488                 Iterator JavaDoc it = result.iterator();
489                 String JavaDoc failedusers = "";
490                 String JavaDoc successusers = "";
491                 while (it.hasNext()) {
492                     UserDataVO data = (UserDataVO) it.next();
493                     if ((data.getPassword() != null) && (data.getPassword().length() > 0)) {
494                         try {
495                             if (doCreate(admin, data, status)) {
496                                 successusers += (":" + data.getUsername());
497                                 successcount++;
498                             }
499                         } catch (Exception JavaDoc e) {
500                             // If things went wrong set status to FAILED
501
String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorsetstatus", "FAILED");
502                             log.error(errMsg, e);
503                             failedusers += (":" + data.getUsername());
504                             failcount++;
505                             if (status == UserDataConstants.STATUS_KEYRECOVERY) {
506                                 admin.setUserStatus(administrator, data.getUsername(), UserDataConstants.STATUS_KEYRECOVERY);
507                             } else {
508                                 admin.setUserStatus(administrator, data.getUsername(), UserDataConstants.STATUS_FAILED);
509                             }
510                         }
511                     } else {
512                         iMsg = intres.getLocalizedMessage("batch.infonoclearpwd", data.getUsername());
513                         log.info(iMsg);
514                     }
515                 }
516
517                 if (failedusers.length() > 0) {
518                     String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorbatchfailed", new Integer JavaDoc(failcount), new Integer JavaDoc(successcount), failedusers);
519                     throw new Exception JavaDoc(errMsg);
520                 }
521                                   
522                 iMsg = intres.getLocalizedMessage("batch.success", new Integer JavaDoc(successcount), successusers);
523                 log.info(iMsg);
524             }
525         } while ((result.size() > 0) && !stopnow);
526
527         log.debug("<createAllWithStatus: " + status);
528     } // createAllWithStatus
529

530     /**
531      * Creates P12-files for one user in the local database.
532      *
533      * @param username username
534      * @throws Exception if the user does not exist or something goes wrong during generation
535      */

536     public void createUser(String JavaDoc username) throws Exception JavaDoc {
537         log.debug(">createUser(" + username + ")");
538
539         IUserAdminSessionRemote admin = adminhome.create();
540         UserDataVO data = admin.findUser(administrator, username);
541         int status = data.getStatus();
542
543         if ((data != null) && (data.getPassword() != null) && (data.getPassword().length() > 0)) {
544             if ((status == UserDataConstants.STATUS_NEW) ||
545                     ((status == UserDataConstants.STATUS_KEYRECOVERY) && usekeyrecovery)) {
546                 try {
547                     doCreate(admin, data, status);
548                 } catch (Exception JavaDoc e) {
549                     // If things went wrong set status to FAILED
550
String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorsetstatus", "FAILED");
551                     log.error(errMsg, e);
552                     if (status == UserDataConstants.STATUS_KEYRECOVERY) {
553                         admin.setUserStatus(administrator, data.getUsername(), UserDataConstants.STATUS_KEYRECOVERY);
554                     } else {
555                         admin.setUserStatus(administrator, data.getUsername(), UserDataConstants.STATUS_FAILED);
556                     }
557                     errMsg = intres.getLocalizedMessage("batch.errorbatchfaileduser", username);
558                     throw new Exception JavaDoc(errMsg);
559                 }
560             } else {
561                 String JavaDoc errMsg = intres.getLocalizedMessage("batch.errorbatchfaileduser", username);
562                 log.error(errMsg);
563                 throw new Exception JavaDoc(errMsg);
564             }
565         }
566
567         log.debug(">createUser(" + username + ")");
568     } // doit
569

570     /**
571      * Main
572      *
573      * @param args command line arguments
574      */

575     public static void main(String JavaDoc[] args) {
576         try {
577             BatchMakeP12 makep12 = new BatchMakeP12();
578             String JavaDoc username = null;
579             String JavaDoc directory = "p12";
580             for (int i = 0; i < args.length; i++) {
581                 if ("-?".equalsIgnoreCase(args[i]) || "--help".equalsIgnoreCase(args[i])){
582                     System.out.println("Usage: batch [username] [-dir directory]");
583                     System.out.println(" username: the name of the user to generate the key.");
584                     System.out.println(" If omitted, keys will be generated for all users with status NEW or FAILED");
585                     System.out.println(" directory: the name of the directory to store the keys to");
586                     System.exit(1);
587                 } else if ("-dir".equalsIgnoreCase(args[i])){
588                     directory = args[++i];
589                 } else {
590                     username = args[i];
591                 }
592             }
593
594             // Create subdirectory 'p12' if it does not exist
595
File JavaDoc dir = new File JavaDoc(directory).getCanonicalFile();
596             dir.mkdir();
597             makep12.setMainStoreDir(directory);
598             String JavaDoc iMsg = intres.getLocalizedMessage("batch.generateindir", dir);
599             log.info(iMsg);
600
601             if (username != null) {
602                 makep12.createUser(username);
603             } else {
604                 // Make P12 for all NEW users in local DB
605
makep12.createAllNew();
606
607                 // Make P12 for all FAILED users in local DB
608
makep12.createAllFailed();
609
610                 // Make P12 for all KEYRECOVERABLE users in local DB
611
makep12.createAllKeyRecover();
612             }
613         } catch (Exception JavaDoc e) {
614             e.printStackTrace();
615             System.exit(1);
616         }
617     } // main
618

619 } // BatchMakeP12
620
Popular Tags