KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > cli > BaseCommand


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;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.PrintStream JavaDoc;
19 import java.rmi.RemoteException JavaDoc;
20 import java.security.KeyFactory JavaDoc;
21 import java.security.KeyStore JavaDoc;
22 import java.security.KeyStoreException JavaDoc;
23 import java.security.NoSuchAlgorithmException JavaDoc;
24 import java.security.NoSuchProviderException JavaDoc;
25 import java.security.PrivateKey JavaDoc;
26 import java.security.cert.CertificateException JavaDoc;
27 import java.security.cert.X509Certificate JavaDoc;
28 import java.security.spec.InvalidKeySpecException JavaDoc;
29 import java.security.spec.PKCS8EncodedKeySpec JavaDoc;
30
31 import javax.ejb.CreateException JavaDoc;
32 import javax.naming.Context JavaDoc;
33 import javax.naming.InitialContext JavaDoc;
34 import javax.naming.NamingException JavaDoc;
35
36 import org.apache.log4j.Logger;
37 import org.ejbca.core.ejb.InitialContextBuilder;
38 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
39 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
40 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionHome;
41 import org.ejbca.core.ejb.ca.publisher.IPublisherSessionRemote;
42 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
43 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
44 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
45 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
46 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
47 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
48 import org.ejbca.core.model.log.Admin;
49 import org.ejbca.util.Base64;
50 import org.ejbca.util.CertTools;
51 import org.ejbca.util.KeyTools;
52
53 /**
54  * Base for Commands, contains useful functions
55  *
56  * @version $Id: BaseCommand.java,v 1.3 2007/01/03 14:49:35 anatom Exp $
57  */

58 public abstract class BaseCommand {
59     /** Log4j instance for Base */
60     private static Logger baseLog = Logger.getLogger(BaseAdminCommand.class);
61     /** Log4j instance for actual class */
62     private Logger log;
63
64     /** UserAdminSession handle, not static since different object should go to different session beans concurrently */
65     private IUserAdminSessionRemote cacheAdmin = null;
66     /** Handle to AdminSessionHome */
67     private static IUserAdminSessionHome cacheHome = null;
68     /** RaAdminSession handle, not static since different object should go to different session beans concurrently */
69     private IRaAdminSessionRemote raadminsession = null;
70     /** Handle to RaAdminSessionHome */
71     private static IRaAdminSessionHome raadminHomesession = null;
72     /** CAAdminSession handle, not static since different object should go to different session beans concurrently */
73     private ICAAdminSessionRemote caadminsession = null;
74     /** Handle to CertificateStoreSessionRemote, not static... */
75     private ICertificateStoreSessionRemote certstoresession = null;
76     /** Handle to PublisherSessionRemote, not static... */
77     private IPublisherSessionRemote publishersession = null;
78     
79     protected Admin administrator = null;
80     
81     /** Where print output of commands */
82     private PrintStream JavaDoc outStream = System.out;
83
84     /** holder of argument array */
85     protected String JavaDoc[] args = null;
86
87     /**
88      * Creates a new default instance of the class
89      *
90      */

91     public BaseCommand() {
92         init(null, Admin.TYPE_CACOMMANDLINE_USER, "cli", System.out);
93     }
94
95     /**
96      * Initialize a new instance of BaseCommand
97      *
98      * @param args command line arguments
99      * @param adminType type of admin Admin.TYPE_RA_USER, or Admin.TYPE_CACOMMANDLINE_USER
100      * @param outStream stream where commands write its output
101      */

102     protected void init(String JavaDoc[] args, int adminType, String JavaDoc adminId, PrintStream JavaDoc outStream) {
103         log = Logger.getLogger(this.getClass());
104         this.args = args;
105         if( outStream != null ) {
106           this.outStream = outStream;
107         }
108         administrator = new Admin(adminType, adminId);
109     }
110
111     /**
112      * Gets InitialContext
113      *
114      * @return InitialContext
115      */

116     protected InitialContext JavaDoc getInitialContext() throws NamingException JavaDoc {
117         baseLog.debug(">getInitialContext()");
118
119         try {
120             InitialContext JavaDoc cacheCtx = InitialContextBuilder.getInstance().getInitialContext();
121             baseLog.debug("<getInitialContext()");
122             return cacheCtx;
123         } catch (NamingException JavaDoc e) {
124             baseLog.error("Can't get InitialContext", e);
125             throw e;
126         }
127     } // getInitialContext
128

129     /** Gets CA admin session
130      *@return ICAAdminSessionRemote
131      */

132     protected ICAAdminSessionRemote getCAAdminSessionRemote() throws Exception JavaDoc{
133         if(caadminsession == null){
134           Context JavaDoc ctx = getInitialContext();
135           ICAAdminSessionHome home = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("CAAdminSession"), ICAAdminSessionHome.class );
136           caadminsession = home.create();
137         }
138         return caadminsession;
139      } // getCAAdminSessionRemote
140

141     /** Gets certificate store session
142      *@return ICertificateStoreSessionRemote
143      */

144     protected ICertificateStoreSessionRemote getCertificateStoreSession() throws Exception JavaDoc{
145         if(certstoresession == null){
146           Context JavaDoc ctx = getInitialContext();
147           ICertificateStoreSessionHome home = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("CertificateStoreSession"), ICertificateStoreSessionHome.class );
148           certstoresession = home.create();
149         }
150         return certstoresession;
151      } // getCertificateStoreSession
152

153     /** Gets publisher session
154      *@return ICertificateStoreSessionRemote
155      */

156     protected IPublisherSessionRemote getPublisherSession() throws Exception JavaDoc{
157         if(publishersession == null){
158           Context JavaDoc ctx = getInitialContext();
159           IPublisherSessionHome home = (IPublisherSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("PublisherSession"), IPublisherSessionHome.class );
160           publishersession = home.create();
161         }
162         return publishersession;
163      } // getPublisherSession
164
/** Gets user admin session
165      *@return InitialContext
166      */

167     protected IUserAdminSessionRemote getAdminSession()
168         throws CreateException JavaDoc, NamingException JavaDoc, RemoteException JavaDoc {
169         debug(">getAdminSession()");
170         try {
171             if (cacheAdmin == null) {
172                 if (cacheHome == null) {
173                     Context JavaDoc jndiContext = getInitialContext();
174                     Object JavaDoc obj1 = jndiContext.lookup("UserAdminSession");
175                     cacheHome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj1,
176                             IUserAdminSessionHome.class);
177                 }
178                 cacheAdmin = cacheHome.create();
179             }
180             debug("<getAdminSession()");
181             return cacheAdmin;
182         } catch (NamingException JavaDoc e) {
183             error("Can't get Admin session", e);
184             throw e;
185         }
186     } // getAdminSession
187

188     /** Gets ra admin session
189      *@return InitialContext
190      */

191     protected IRaAdminSessionRemote getRaAdminSession() throws CreateException JavaDoc, NamingException JavaDoc, RemoteException JavaDoc {
192         debug(">getRaAdminSession()");
193         administrator = new Admin(Admin.TYPE_RA_USER);
194         try {
195             if( raadminsession == null ) {
196                 if (raadminHomesession == null) {
197                     Context JavaDoc jndiContext = getInitialContext();
198                     Object JavaDoc obj1 = jndiContext.lookup("RaAdminSession");
199                     raadminHomesession = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj1, IRaAdminSessionHome.class);
200                 }
201                 raadminsession = raadminHomesession.create();
202             }
203             debug("<getRaAdminSession()");
204             return raadminsession;
205         } catch (NamingException JavaDoc e ) {
206             error("Can't get RaAdmin session", e);
207             throw e;
208         }
209     } // getRaAdminSession
210

211     /**
212      * Method checking if the application server is running.
213      *
214      * @return true if app server is running.
215      */

216     protected boolean appServerRunning() {
217         // Check that the application server is running by getting a home interface for user admin session
218
try {
219             Context JavaDoc ctx = getInitialContext();
220             ICAAdminSessionHome home = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("CAAdminSession"),ICAAdminSessionHome.class);
221             home.getClass(); // avoid PMD warning :)
222
return true;
223         } catch (Exception JavaDoc e) {
224             error("Appserver not running: ", e);
225             return false;
226         }
227     }
228
229     /** Private key with length 1024 bits */
230     static byte[] keys1024bit = Base64.decode(
231     ("MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKA5rNhYbPuVcArT"
232     +"mkthfrW2tX1Z7SkCD01sDYrkiwOcodFmS1cSyz8eHM51iwHA7CW0WFvfUjomBT5y"
233     +"gRQfIsf5M5DUtYcKM1hmGKSPzvmF4nYv+3UBUesCvBXVRN/wFZ44SZZ3CVvpQUYb"
234     +"GWjyC+Dgol5n8oKOC287rnZUPEW5AgMBAAECgYEAhMtoeyLGqLlRVFfOoL1cVGTr"
235     +"BMp8ail/30435y7GHKc74p6iwLcd5uEhROhc3oYz8ogHV5W+w9zxKbGjU7b+jmh+"
236     +"h/WFao+Gu3sSrZ7ieg95fSuQsBlJp3w+eCAOZwlEu/JQQHDtURui25SPVblZ9/41"
237     +"u8VwFjk9YQx+nT6LclECQQDYlC9bOr1SWL8PBlipXB/UszMsTM5xEH920A+JPF4E"
238     +"4tw+AHecanjr5bXSluRbWSWUjtl5LV2edqAP9EsH1/A1AkEAvWOctUvTlm6fWHJq"
239     +"lZhsWVvOhDG7cn5gFu34J8JJd5QHov0469CpSamY0Q/mPE/y3kDllmyYvnQ+yobB"
240     +"ZRg39QJBAINCM/0/eVQ58vlBKGTkL2pyfNYhapB9pjK04GWVD4o4j7CICfXjVYvq"
241     +"eSq7RoTSX4NMnCLjyrRqQpHIxdxoE+0CQQCz7MzWWGF+Cz6LUrf7w0E8a8H5SR4i"
242     +"GfnEDvSxIR2W4yWWLShEsIoEF4G9LHO5XOMJT3JOxIEgf2OgGQHmv2l5AkBThYUo"
243     +"ni82jZuue3YqXXHY2lz3rVmooAv7LfQ63yzHECFsQz7kDwuRVWWRsoCOURtymAHp"
244     +"La09g2BE+Q5oUUFx").getBytes());
245     /** self signed cert done with above private key */
246     static byte[] certbytes = Base64.decode(
247     ("MIICNzCCAaCgAwIBAgIIIOqiVwJHz+8wDQYJKoZIhvcNAQEFBQAwKzENMAsGA1UE"
248     +"AxMEVGVzdDENMAsGA1UEChMEVGVzdDELMAkGA1UEBhMCU0UwHhcNMDQwNTA4MDkx"
249     +"ODMwWhcNMDUwNTA4MDkyODMwWjArMQ0wCwYDVQQDEwRUZXN0MQ0wCwYDVQQKEwRU"
250     +"ZXN0MQswCQYDVQQGEwJTRTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAgbf2"
251     +"Sv34lsY43C8WJjbUd57TNuHJ6p2Es7ojS3D2yxtzQg/A8wL1OfXes344PPNGHkDd"
252     +"QPBaaWYQrvLvqpjKwx/vA1835L3I92MsGs+uivq5L5oHfCxEh8Kwb9J2p3xjgeWX"
253     +"YdZM5dBj3zzyu+Jer4iU4oCAnnyG+OlVnPsFt6ECAwEAAaNkMGIwDwYDVR0TAQH/"
254     +"BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0GA1UdDgQWBBQArVZXuGqbb9yhBLbu"
255     +"XfzjSuXfHTAfBgNVHSMEGDAWgBQArVZXuGqbb9yhBLbuXfzjSuXfHTANBgkqhkiG"
256     +"9w0BAQUFAAOBgQA1cB6wWzC2rUKBjFAzfkLvDUS3vEMy7ntYMqqQd6+5s1LHCoPw"
257     +"eaR42kMWCxAbdSRgv5ATM0JU3Q9jWbLO54FkJDzq+vw2TaX+Y5T+UL1V0o4TPKxp"
258     +"nKuay+xl5aoUcVEs3h3uJDjcpgMAtyusMEyv4d+RFYvWJWFzRTKDueyanw==").getBytes());
259
260     /**
261      * Method checking if strong crypto is installed (extra package from java.sun.com)
262      *
263      * @return true if strong crypto is installed.
264      */

265     protected boolean strongCryptoInstalled() throws IOException JavaDoc, KeyStoreException JavaDoc, CertificateException JavaDoc, NoSuchProviderException JavaDoc, NoSuchAlgorithmException JavaDoc, InvalidKeySpecException JavaDoc {
266         CertTools.installBCProvider();
267         X509Certificate JavaDoc cert = CertTools.getCertfromByteArray(certbytes);
268         PKCS8EncodedKeySpec JavaDoc pkKeySpec = new PKCS8EncodedKeySpec JavaDoc(keys1024bit);
269         KeyFactory JavaDoc keyFactory = KeyFactory.getInstance("RSA");
270         PrivateKey JavaDoc pk = keyFactory.generatePrivate(pkKeySpec);
271         KeyStore JavaDoc ks = KeyTools.createP12("Foo", pk, cert, (X509Certificate JavaDoc)null);
272         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
273         // If password below is more than 7 chars, strong crypto is needed
274
ks.store(baos, "foo1234567890".toCharArray());
275         // If we didn't throw an exception, we were succesful
276
return true;
277     }
278
279     /**
280      * Logs a message with priority DEBUG
281      *
282      * @param msg Message
283      */

284     public void debug(String JavaDoc msg) {
285         log.debug(msg);
286     }
287
288     /**
289      * Logs a message and an exception with priority DEBUG
290      *
291      * @param msg Message
292      * @param t Exception
293      */

294     public void debug(String JavaDoc msg, Throwable JavaDoc t) {
295         log.debug(msg, t);
296     }
297
298     /**
299      * Logs a message with priority INFO
300      *
301      * @param msg Message
302      */

303     public void info(String JavaDoc msg) {
304         log.info(msg);
305     }
306
307     /**
308      * Logs a message and an exception with priority INFO
309      *
310      * @param msg Message
311      * @param t Exception
312      */

313     public void info(String JavaDoc msg, Throwable JavaDoc t) {
314         log.info(msg, t);
315     }
316
317     /**
318      * Logs a message with priority ERROR
319      *
320      * @param msg Message
321      */

322     public void error(String JavaDoc msg) {
323         log.error(msg);
324     }
325
326     /**
327      * Logs a message and an exception with priority ERROR
328      *
329      * @param msg Message
330      * @param t Exception
331      */

332     public void error(String JavaDoc msg, Throwable JavaDoc t) {
333         log.error(msg, t);
334     }
335
336
337     /**
338      * Return the PrintStream used to print output of commands
339      *
340      */

341     public PrintStream JavaDoc getOutputStream() {
342         return outStream;
343     }
344
345     /**
346      * Set the PrintStream used to print output of commands
347      *
348      * @param outStream stream where commands write its output
349      */

350     public void setOutputStream(PrintStream JavaDoc outStream) {
351     if( outStream == null )
352         this.outStream = System.out;
353     else
354         this.outStream = outStream;
355     }
356
357 } //BaseCommand
358
Popular Tags