KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > protocol > ws > client > GenerateNewUserCommand


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.protocol.ws.client;
15
16 import java.io.File JavaDoc;
17 import java.io.FileInputStream JavaDoc;
18 import java.io.FileNotFoundException JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.ArrayList JavaDoc;
22
23 import org.ejbca.core.model.SecConst;
24 import org.ejbca.core.model.ra.UserDataConstants;
25 import org.ejbca.core.protocol.ws.client.gen.AuthorizationDeniedException_Exception;
26 import org.ejbca.core.protocol.ws.client.gen.Certificate;
27 import org.ejbca.core.protocol.ws.client.gen.UserDataVOWS;
28 import org.ejbca.core.protocol.ws.client.gen.UserDoesntFullfillEndEntityProfile_Exception;
29 import org.ejbca.core.protocol.ws.common.CertificateHelper;
30 import org.ejbca.ui.cli.ErrorAdminCommandException;
31 import org.ejbca.ui.cli.IAdminCommand;
32 import org.ejbca.ui.cli.IllegalAdminCommandException;
33 import org.ejbca.util.CertTools;
34
35
36
37
38
39 /**
40  * Adds a user to the database.
41  *
42  * @version $Id: GenerateNewUserCommand.java,v 1.2 2006/10/08 22:53:26 herrvendil Exp $
43  */

44 public class GenerateNewUserCommand extends EJBCAWSRABaseCommand implements IAdminCommand{
45
46     
47     private static final int ARG_USERNAME = 1;
48     private static final int ARG_PASSWORD = 2;
49     private static final int ARG_CLEARPWD = 3;
50     private static final int ARG_SUBJECTDN = 4;
51     private static final int ARG_SUBJECTALTNAME = 5;
52     private static final int ARG_EMAIL = 6;
53     private static final int ARG_CA = 7;
54     private static final int ARG_TYPE = 8;
55     private static final int ARG_TOKEN = 9;
56     private static final int ARG_STATUS = 10;
57     private static final int ARG_ENDENTITYPROFILE = 11;
58     private static final int ARG_CERTIFICATEPROFILE = 12;
59     private static final int ARG_ISSUERALIAS = 13;
60     private static final int ARG_PKCS10 = 14;
61     private static final int ARG_ENCODING = 15;
62     private static final int ARG_HARDTOKENSN = 16;
63     private static final int ARG_OUTPUTPATH = 17;
64     
65     /**
66      * Creates a new instance of RaAddUserCommand
67      *
68      * @param args command line arguments
69      */

70     public GenerateNewUserCommand(String JavaDoc[] args) {
71         super(args);
72     }
73
74     /**
75      * Runs the command
76      *
77      * @throws IllegalAdminCommandException Error in command args
78      * @throws ErrorAdminCommandException Error running command
79      */

80     public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {
81
82         try {
83            
84             if(args.length < 17 || args.length > 18){
85                 usage();
86                 System.exit(-1);
87             }
88             
89             UserDataVOWS userdata = new UserDataVOWS();
90             userdata.setUsername(args[ARG_USERNAME]);
91             userdata.setPassword(args[ARG_PASSWORD]);
92             userdata.setClearPwd(args[ARG_CLEARPWD].equalsIgnoreCase("true"));
93             userdata.setSubjectDN(args[ARG_SUBJECTDN]);
94             if(!args[ARG_SUBJECTALTNAME].equalsIgnoreCase("NULL")){
95                 userdata.setSubjectAltName(args[ARG_SUBJECTALTNAME]);
96             }
97             if(!args[ARG_EMAIL].equalsIgnoreCase("NULL")){
98                 userdata.setEmail(args[ARG_EMAIL]);
99             }
100             userdata.setCaName(args[ARG_CA]);
101             userdata.setTokenType(args[ARG_TOKEN]);
102             userdata.setStatus(getStatus(args[ARG_STATUS]));
103             userdata.setEndEntityProfileName(args[ARG_ENDENTITYPROFILE]);
104             userdata.setCertificateProfileName(args[ARG_CERTIFICATEPROFILE]);
105             
106             int type = Integer.parseInt(args[ARG_TYPE]);
107             
108             if((type & SecConst.USER_SENDNOTIFICATION) != 0){
109                 userdata.setSendNotification(true);
110             }
111             if((type & SecConst.USER_KEYRECOVERABLE) != 0){
112                 userdata.setKeyRecoverable(true);
113             }
114
115             if(!args[ARG_ISSUERALIAS].equalsIgnoreCase("NONE")){
116                 userdata.setEmail(args[ARG_ISSUERALIAS]);
117             }
118             
119             String JavaDoc username = args[ARG_USERNAME];
120             String JavaDoc password = args[ARG_PASSWORD];
121             String JavaDoc pkcs10 = getPKCS10(args[ARG_PKCS10]);
122             String JavaDoc encoding = getEncoding(args[ARG_ENCODING]);
123             String JavaDoc hardtokensn = getHardTokenSN(args[ARG_HARDTOKENSN]);
124             String JavaDoc outputPath = null;
125             if(args.length == 18){
126                 outputPath = getOutputPath(args[ARG_OUTPUTPATH]);
127             }
128             
129             getPrintStream().println("Trying to add user:");
130             getPrintStream().println("Username: "+userdata.getUsername());
131             getPrintStream().println("Subject DN: "+userdata.getSubjectDN());
132             getPrintStream().println("Subject Altname: "+userdata.getSubjectAltName());
133             getPrintStream().println("Email: "+userdata.getEmail());
134             getPrintStream().println("CA Name: "+userdata.getCaName());
135             getPrintStream().println("Type: "+type);
136             getPrintStream().println("Token: "+userdata.getTokenType());
137             getPrintStream().println("Status: "+userdata.getStatus());
138             getPrintStream().println("End entity profile: "+userdata.getEndEntityProfileName());
139             getPrintStream().println("Certificate profile: "+userdata.getCertificateProfileName());
140
141             if(userdata.getHardTokenIssuerName() == null){
142                 getPrintStream().println("Hard Token Issuer Alias: NONE");
143             }else{
144                 getPrintStream().println("Hard Token Issuer Alias: " + userdata.getHardTokenIssuerName());
145             }
146             
147             
148             try{
149                 getEjbcaRAWS().editUser(userdata);
150                 getPrintStream().println("User '"+userdata.getUsername()+"' has been added/edited.");
151                 getPrintStream().println();
152                 
153                 Certificate result = getEjbcaRAWS().pkcs10Req(username,password,pkcs10,hardtokensn);
154                 
155                 if(result==null){
156                     getPrintStream().println("No certificate could be generated for user, check server logs for error.");
157                 }else{
158                     String JavaDoc filepath = username;
159                     if(encoding.equals("DER")){
160                         filepath += ".cer";
161                     }else{
162                         filepath += ".pem";
163                     }
164                     if(outputPath != null){
165                         filepath = outputPath + "/" + filepath;
166                     }
167                     
168                     
169                     if(encoding.equals("DER")){
170                         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(filepath);
171                         fos.write(CertificateHelper.getCertificate(result.getCertificateData()).getEncoded());
172                         fos.close();
173                     }else{
174                         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(filepath);
175                         ArrayList JavaDoc<java.security.cert.Certificate JavaDoc> list = new ArrayList JavaDoc<java.security.cert.Certificate JavaDoc>();
176                         list.add(CertificateHelper.getCertificate(result.getCertificateData()));
177                         fos.write(CertTools.getPEMFromCerts(list));
178                         fos.close();
179                     }
180                     getPrintStream().println("Certificate generated, written to " + filepath);
181                 }
182             }catch(AuthorizationDeniedException_Exception e){
183                 getPrintStream().println("Error : " + e.getMessage());
184             }catch(UserDoesntFullfillEndEntityProfile_Exception e){
185                 getPrintStream().println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage());
186             }
187         } catch (Exception JavaDoc e) {
188             throw new ErrorAdminCommandException(e);
189         }
190     }
191
192     private int getStatus(String JavaDoc status) {
193         if(status.equalsIgnoreCase("NEW")){
194             return UserDataConstants.STATUS_NEW;
195         }
196         if(status.equalsIgnoreCase("INPROCESS")){
197             return UserDataConstants.STATUS_INPROCESS;
198         }
199         if(status.equalsIgnoreCase("FAILED")){
200             return UserDataConstants.STATUS_FAILED;
201         }
202         if(status.equalsIgnoreCase("HISTORICAL")){
203             return UserDataConstants.STATUS_HISTORICAL;
204         }
205         
206         getPrintStream().println("Error in status string : " + status );
207         usage();
208         System.exit(-1);
209         return 0;
210     }
211     
212     private String JavaDoc getHardTokenSN(String JavaDoc hardtokensn) {
213         if(hardtokensn.equalsIgnoreCase("NONE")){
214           return null;
215         }
216         
217         return hardtokensn;
218     }
219     
220     private String JavaDoc getPKCS10(String JavaDoc pkcs10Path) {
221         String JavaDoc retval=null;
222         try {
223             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(pkcs10Path);
224             byte[] contents = new byte[fis.available()];
225             fis.read(contents);
226             fis.close();
227             retval = new String JavaDoc(contents);
228         } catch (FileNotFoundException JavaDoc e) {
229             getPrintStream().println("Error : PKCS10 file couln't be found.");
230             System.exit(-1);
231         } catch (IOException JavaDoc e) {
232             getPrintStream().println("Error reading content of PKCS10 file.");
233             System.exit(-1);
234         }
235         
236         
237         return retval;
238     }
239
240     private String JavaDoc getOutputPath(String JavaDoc outputpath) {
241         File JavaDoc dir = new File JavaDoc(outputpath);
242         if(!dir.exists()){
243             getPrintStream().println("Error : Output directory doesn't seem to exist.");
244             System.exit(-1);
245         }
246         if(!dir.isDirectory()){
247             getPrintStream().println("Error : Output directory doesn't seem to be a directory.");
248             System.exit(-1);
249         }
250         if(!dir.canWrite()){
251             getPrintStream().println("Error : Output directory isn't writeable.");
252             System.exit(-1);
253
254         }
255         return outputpath;
256     }
257
258     private String JavaDoc getEncoding(String JavaDoc encoding) {
259         if(!encoding.equalsIgnoreCase("PEM") && !encoding.equalsIgnoreCase("DER")){
260             usage();
261             System.exit(-1);
262         }
263         
264         return encoding.toUpperCase();
265     }
266
267
268     protected void usage() {
269         getPrintStream().println("Command used to add or edit userdata and to generate the user in one step.");
270         getPrintStream().println("Usage : generatenewuser <username> <password> <clearpwd (true|false)> <subjectdn> <subjectaltname or NULL> <email or NULL> <caname> <type> <token> <status> <endentityprofilename> <certificateprofilename> <issueralias (or NONE)> <pkcs10path> <encoding (DER|PEM)> <hardtokensn (or NONE)> <outputpath (optional)>\n\n");
271         getPrintStream().println("DN is of form \"C=SE, O=MyOrg, OU=MyOrgUnit, CN=MyName\" etc.");
272         getPrintStream().println(
273             "SubjectAltName is of form \"rfc822Name=<email>, dNSName=<host name>, uri=<http://host.com/>, ipaddress=<address>, guid=<globally unique id>\"");
274
275         getPrintStream().println("Type (mask): INVALID=0; END-USER=1; KEYRECOVERABLE=128; SENDNOTIFICATION=256");
276         
277         getPrintStream().print("Existing tokens : " + "USERGENERATED" + ", " +
278                 "P12" + ", "+ "JKS" + ", " + "PEM");
279         getPrintStream().print("Existing statuses (new users will always be set as NEW) : NEW, INPROCESS, FAILED, HISTORICAL");
280         getPrintStream().println("outputpath : directory where certificate is written in form username+.cer|.pem ");
281     }
282
283
284 }
285
Popular Tags