summaryrefslogtreecommitdiffstats
path: root/pki/base/silent/src/com
diff options
context:
space:
mode:
Diffstat (limited to 'pki/base/silent/src/com')
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java1069
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java964
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java871
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java1681
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java975
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java804
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java2136
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java14
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/PKISilent.java97
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java53
-rwxr-xr-xpki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java4126
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java2792
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java51
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java52
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java65
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java53
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java54
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java1169
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java809
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java42
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java133
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java118
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java195
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java377
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java23
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java8
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java228
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java78
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java104
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java22
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java44
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Request.java335
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java88
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java705
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java153
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java63
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java124
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java31
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java1208
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java2413
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java605
46 files changed, 13056 insertions, 12134 deletions
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
index 9bcebea3..337bf927 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,7 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -41,8 +41,10 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
+
public class ConfigureCA {
+
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
@@ -55,7 +57,7 @@ public class ConfigureCA {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ca/admin/console/config/login";
public static String wizard_uri = "/ca/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -75,7 +77,7 @@ public class ConfigureCA {
public static String sd_admin_name = null;
public static String sd_admin_password = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -160,7 +162,7 @@ public class ConfigureCA {
public static String ca_audit_signing_cert_pp = null;
public static String ca_audit_signing_cert_cert = null;
- // names
+ // names
public static String ca_sign_cert_subject_name = null;
public static String ca_subsystem_cert_subject_name = null;
public static String ca_ocsp_cert_subject_name = null;
@@ -169,7 +171,7 @@ public class ConfigureCA {
public static String subsystem_name = null;
- public static String external_ca = null;
+ public static String external_ca= null;
public static String ext_ca_cert_file = null;
public static String ext_ca_cert_chain_file = null;
public static String ext_csr_file = null;
@@ -180,9 +182,10 @@ public class ConfigureCA {
public static String clone_p12_passwd = null;
public static String clone_p12_file = null;
- // for correct selection of CA to be cloned
+ //for correct selection of CA to be cloned
public static String urls;
+
public ConfigureCA() {// do nothing :)
}
@@ -201,35 +204,36 @@ public class ConfigureCA {
return status;
}
- public boolean checkStatus(HTTPResponse hr, String name, String expected,
- String location) {
- return checkStatus(hr, name, new String[] { expected }, location);
- }
+ public boolean checkStatus(HTTPResponse hr, String name,
+ String expected, String location) {
+ return checkStatus(hr,name, new String[] {expected}, location);
+ }
- public boolean checkStatus(HTTPResponse hr, String name, String[] expected,
- String location) {
+ public boolean checkStatus(HTTPResponse hr, String name,
+ String[] expected, String location) {
String status = getStatus(hr, name);
if (status == null) {
- System.out.println("Error in " + location + ": " + name
- + " value is null");
+ System.out.println("Error in " + location + ": " + name +
+ " value is null");
return false;
- }
- for (int i = 0; i < expected.length; i++) {
+ }
+ for (int i=0; i< expected.length; i++) {
if (status.equals(expected[i])) {
return true;
}
}
- System.out.println("Error in " + location + ": " + name + " returns "
- + status);
+ System.out.println("Error in " + location + ": " + name +
+ " returns " + status);
return false;
- }
+ }
+
public boolean LoginPanel() {
try {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "pin=" + pin + "&xml=true";
+ String query_string = "pin=" + pin + "&xml=true";
hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
System.out.println("xml returned: " + hr.getHTML());
@@ -246,8 +250,8 @@ public class ConfigureCA {
hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
- if (!checkStatus(hr, "status", "display", "LoginPanel()")) {
+ "p=0&op=next&xml=true");
+ if (! checkStatus(hr, "status", "display", "LoginPanel()")) {
return false;
}
@@ -268,40 +272,33 @@ public class ConfigureCA {
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token") + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "TokenChoicePanel()")) {
+ + URLEncoder.encode("Internal Key Storage Token") + "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
} // HSM
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "TokenChoicePanel()")) {
+ + URLEncoder.encode(token_name) + "&__uPasswd="
+ + URLEncoder.encode(token_pwd) + "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "TokenChoicePanel()")) {
+ + URLEncoder.encode(token_name) + "";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
}
return true;
} catch (Exception e) {
- System.out.println("Exception in TokenChoicePanel(): "
- + e.toString());
+ System.out.println("Exception in TokenChoicePanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -313,20 +310,19 @@ public class ConfigureCA {
String domain_url = "https://" + cs_hostname + ":" + cs_port;
String query_string = null;
- if (!clone) {
+ if (! clone) {
query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&sdomainName=" + URLEncoder.encode(domain_name)
- + "&choice=newdomain" + "&p=3" + "&op=next"
- + "&xml=true";
+ + "&sdomainName=" + URLEncoder.encode(domain_name)
+ + "&choice=newdomain" + "&p=3" + "&op=next" + "&xml=true";
} else {
- domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
+ domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&sdomainName=" + "&choice=existingdomain" + "&p=3"
- + "&op=next" + "&xml=true";
+ + "&sdomainName="
+ + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "DomainPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "DomainPanel()")) {
return false;
}
@@ -342,11 +338,10 @@ public class ConfigureCA {
try {
HTTPResponse hr = null;
String query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
return true;
} catch (Exception e) {
- System.out.println("Exception in DisplayCertChainPanel(): "
- + e.toString());
+ System.out.println("Exception in DisplayCertChainPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -357,83 +352,78 @@ public class ConfigureCA {
boolean st = false;
HTTPResponse hr = null;
- String subca_url = "https://" + cs_hostname + ":" + cs_port
- + "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA";
+ String subca_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA" ;
String query_string = "url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(subca_url);
+ String query_string_1 = "uid=" + sd_admin_name + "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(subca_url) ;
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
// get session id from security domain
-
+
String subca_session_id = hr.getContentValue("header.session_id");
String subca_url_1 = hr.getContentValue("header.url");
-
- System.out.println("SUBCA_SESSION_ID=" + subca_session_id);
- System.out.println("SUBCA_URL=" + subca_url_1);
+
+ System.out.println("SUBCA_SESSION_ID=" + subca_session_id );
+ System.out.println("SUBCA_URL=" + subca_url_1 );
// use session id to connect back to subCA
- String query_string_2 = "p=5" + "&subsystem=CA" + "&session_id="
- + subca_session_id + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ String query_string_2 = "p=5" + "&subsystem=CA" +
+ "&session_id=" + subca_session_id + "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, query_string_2);
urls = hr.getHTML();
int indx = urls.indexOf(clone_uri);
if (indx < 0) {
throw new Exception("Invalid clone_uri");
}
- urls = urls.substring(urls.lastIndexOf("<option", indx), indx);
+ urls = urls.substring(urls.lastIndexOf("<option" , indx), indx);
urls = urls.split("\"")[1];
System.out.println("urls =" + urls);
- return true;
+ return true;
} catch (Exception e) {
- System.out.println("Exception in SecurityDomainLoginPanel(): "
- + e.toString());
+ System.out.println("Exception in SecurityDomainLoginPanel(): " + e.toString());
e.printStackTrace();
return false;
}
}
public boolean CreateCAPanel() {
- try {
+ try {
boolean st = false;
HTTPResponse hr = null;
String query_string = null;
if (!clone) {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=newsubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name);
+ + "&choice=newsubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name);
} else {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=clonesubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name) + "&urls=" + urls
- + "";
+ + "&choice=clonesubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name)
+ + "&urls=" + urls + "";
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel()")) {
return false;
}
if (clone) {
hr = null;
- query_string = "p=6" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "CreateCAPanel(2)")) {
+ query_string = "p=6" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "CreateCAPanel(2)")) {
return false;
}
}
@@ -450,44 +440,42 @@ public class ConfigureCA {
try {
HTTPResponse hr = null;
- String query_string = "p=7" + "&op=next" + "&xml=true"
- + "&__password=" + URLEncoder.encode(clone_p12_passwd)
- + "&path=" + URLEncoder.encode(clone_p12_file) + "";
+ String query_string = "p=7" + "&op=next" + "&xml=true"
+ + "&__password=" + URLEncoder.encode(clone_p12_passwd)
+ + "&path=" + URLEncoder.encode(clone_p12_file) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "RestoreKeyCertPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "RestoreKeyCertPanel()")) {
return false;
}
return true;
} catch (Exception e) {
- System.out.println("Exception in RestoreKeyCertPanel(): "
- + e.toString());
+ System.out.println("Exception in RestoreKeyCertPanel(): " + e.toString());
e.printStackTrace();
return false;
}
}
+
public boolean HierarchyPanel() {
- try {
+ try {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "p=8" + "&op=next" + "&xml=true";
- if (external_ca.equalsIgnoreCase("true"))
+ String query_string = "p=8" + "&op=next" + "&xml=true" ;
+ if (external_ca.equalsIgnoreCase("true"))
query_string += "&choice=join";
else
- query_string += "&choice=root";
+ query_string += "&choice=root";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "HierarchyPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "HierarchyPanel()")) {
return false;
}
return true;
} catch (Exception e) {
- System.out
- .println("Exception in HierarchyPanel(): " + e.toString());
+ System.out.println("Exception in HierarchyPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -499,38 +487,26 @@ public class ConfigureCA {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "p=9"
- + "&op=next"
- + "&xml=true"
- + "&host="
- + URLEncoder.encode(ldap_host)
- + "&port="
- + URLEncoder.encode(ldap_port)
- + "&binddn="
- + URLEncoder.encode(bind_dn)
- + "&__bindpwd="
- + URLEncoder.encode(bind_password)
- + "&basedn="
- + URLEncoder.encode(base_dn)
- + "&database="
- + URLEncoder.encode(db_name)
- + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true") ? "&secureConn=on" : "")
- + (clone_start_tls.equals("true") ? "&cloneStartTLS=on"
- : "")
- + (remove_data.equals("true") ? "&removeData=true" : "");
+ String query_string = "p=9" + "&op=next" + "&xml=true" + "&host="
+ + URLEncoder.encode(ldap_host) + "&port="
+ + URLEncoder.encode(ldap_port) + "&binddn="
+ + URLEncoder.encode(bind_dn) + "&__bindpwd="
+ + URLEncoder.encode(bind_password) + "&basedn="
+ + URLEncoder.encode(base_dn) + "&database="
+ + URLEncoder.encode(db_name) + "&display="
+ + URLEncoder.encode("$displayStr")
+ + (secure_conn.equals("true")? "&secureConn=on": "")
+ + (clone_start_tls.equals("true")? "&cloneStartTLS=on": "")
+ + (remove_data.equals("true")? "&removeData=true": "");
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "LdapConnectionPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "LdapConnectionPanel()")) {
return false;
}
return true;
} catch (Exception e) {
- System.out.println("Exception in LdapConnectionPanel(): "
- + e.toString());
+ System.out.println("Exception in LdapConnectionPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -545,70 +521,48 @@ public class ConfigureCA {
ArrayList<String> al = null;
String query_string = null;
if (clone) {
- query_string = "p=10" + "&op=next" + "&xml=true"
- + "&sslserver_custom_size=" + sslserver_key_size
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename + "&sslserver_choice=custom"
- + "&sslserver_keytype=" + sslserver_key_type
- + "&choice=custom" + "&keytype=" + key_type
- + "&custom_size=" + key_size;
+ query_string = "p=10" + "&op=next" + "&xml=true"
+ + "&sslserver_custom_size=" + sslserver_key_size
+ + "&sslserver_custom_curvename=" + sslserver_key_curvename
+ + "&sslserver_choice=custom"
+ + "&sslserver_keytype=" + sslserver_key_type
+ + "&choice=custom" + "&keytype=" + key_type
+ + "&custom_size=" + key_size;
} else {
query_string = "p=10" + "&op=next" + "&xml=true"
- + "&subsystem_custom_size="
- + subsystem_key_size
- + "&subsystem_custom_curvename="
- + subsystem_key_curvename
- + "&subsystem_keytype="
- + subsystem_key_type
- + "&subsystem_choice=custom"
- + "&sslserver_custom_size="
- + sslserver_key_size
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename
- + "&sslserver_keytype="
- + sslserver_key_type
- + "&sslserver_choice=custom"
- + "&signing_custom_size="
- + signing_key_size
- + "&signing_custom_curvename="
- + signing_key_curvename
- + "&signing_keytype="
- + signing_key_type
- + "&signing_choice=custom"
- + "&signing_keyalgorithm="
- + key_algorithm
- + "&signing_signingalgorithm="
- + signing_signingalgorithm
- + "&ocsp_signing_custom_size="
- + ocsp_signing_key_size
- + "&ocsp_signing_custom_curvename="
- + ocsp_signing_key_curvename
- + "&ocsp_signing_keytype="
- + ocsp_signing_key_type
- + "&ocsp_signing_choice=custom"
- + "&ocsp_signing_signingalgorithm="
- + ocsp_signing_signingalgorithm
- + "&audit_signing_custom_size="
- + audit_signing_key_size
- + "&audit_signing_custom_curvename="
- + audit_signing_key_curvename
- + "&audit_signing_keytype="
- + audit_signing_key_type
- + "&audit_signing_choice=custom"
- + "&custom_size="
- + key_size
- + "&custom_curvename="
- + key_curvename
- + "&keytype="
- + key_type
- + "&choice=custom"
- + "&signingalgorithm="
- + signing_algorithm
- + "&keyalgorithm=" + key_algorithm;
+ + "&subsystem_custom_size=" + subsystem_key_size
+ + "&subsystem_custom_curvename=" + subsystem_key_curvename
+ + "&subsystem_keytype=" + subsystem_key_type
+ + "&subsystem_choice=custom"
+ + "&sslserver_custom_size=" + sslserver_key_size
+ + "&sslserver_custom_curvename=" + sslserver_key_curvename
+ + "&sslserver_keytype=" + sslserver_key_type
+ + "&sslserver_choice=custom"
+ + "&signing_custom_size=" + signing_key_size
+ + "&signing_custom_curvename=" + signing_key_curvename
+ + "&signing_keytype=" + signing_key_type
+ + "&signing_choice=custom"
+ + "&signing_keyalgorithm=" + key_algorithm
+ + "&signing_signingalgorithm=" + signing_signingalgorithm
+ + "&ocsp_signing_custom_size=" + ocsp_signing_key_size
+ + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename
+ + "&ocsp_signing_keytype=" + ocsp_signing_key_type
+ + "&ocsp_signing_choice=custom"
+ + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm
+ + "&audit_signing_custom_size=" + audit_signing_key_size
+ + "&audit_signing_custom_curvename=" + audit_signing_key_curvename
+ + "&audit_signing_keytype=" + audit_signing_key_type
+ + "&audit_signing_choice=custom"
+ + "&custom_size=" + key_size
+ + "&custom_curvename=" + key_curvename
+ + "&keytype=" + key_type
+ + "&choice=custom"
+ + "&signingalgorithm=" + signing_algorithm
+ + "&keyalgorithm=" + key_algorithm;
}
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "KeyPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "KeyPanel()")) {
return false;
}
@@ -620,7 +574,7 @@ public class ConfigureCA {
// get ca cert subject name
if (al != null) {
for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
+ String temp = al.get(i);
if (temp.indexOf("Certificate Authority") > 0) {
ca_cert_name = temp;
@@ -635,13 +589,13 @@ public class ConfigureCA {
}
}
}
-
+
System.out.println("default: ca_cert_name=" + ca_cert_name);
System.out.println("default: ocsp_cert_name=" + ocsp_cert_name);
- System.out.println("default: ca_subsystem_cert_name="
- + ca_subsystem_cert_name);
- System.out.println("default: ca_audit_signing_cert_name="
- + ca_audit_signing_cert_name);
+ System.out.println(
+ "default: ca_subsystem_cert_name=" + ca_subsystem_cert_name);
+ System.out.println(
+ "default: ca_audit_signing_cert_name=" + ca_audit_signing_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
return true;
} catch (Exception e) {
@@ -665,33 +619,28 @@ public class ConfigureCA {
// use subject names provided as input
if (!clone) {
- query_string = "p=11" + "&op=next" + "&xml=true"
- + "&subsystem="
- + URLEncoder.encode(ca_subsystem_cert_subject_name)
- + "&ocsp_signing="
- + URLEncoder.encode(ca_ocsp_cert_subject_name)
- + "&signing="
- + URLEncoder.encode(ca_sign_cert_subject_name)
- + "&sslserver="
- + URLEncoder.encode(ca_server_cert_subject_name)
- + "&audit_signing="
- + URLEncoder.encode(ca_audit_signing_cert_subject_name)
- + "&urls=0" + "";
+ query_string = "p=11" + "&op=next" + "&xml=true" + "&subsystem="
+ + URLEncoder.encode(ca_subsystem_cert_subject_name)
+ + "&ocsp_signing="
+ + URLEncoder.encode(ca_ocsp_cert_subject_name) + "&signing="
+ + URLEncoder.encode(ca_sign_cert_subject_name) + "&sslserver="
+ + URLEncoder.encode(ca_server_cert_subject_name) + "&audit_signing="
+ + URLEncoder.encode(ca_audit_signing_cert_subject_name) + "&urls=0"
+ + "";
} else {
- query_string = "p=11" + "&op=next" + "&xml=true"
- + "&sslserver="
- + URLEncoder.encode(ca_server_cert_subject_name)
- + "&urls=0" + "";
- }
+ query_string = "p=11" + "&op=next" + "&xml=true" + "&sslserver="
+ + URLEncoder.encode(ca_server_cert_subject_name) + "&urls=0"
+ + "";
+ }
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "CertSubjectPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "CertSubjectPanel()")) {
return false;
}
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
req_list = px.constructValueList("CertReqPair", "Request");
cert_list = px.constructValueList("CertReqPair", "Certificate");
dn_list = px.constructValueList("CertReqPair", "Nickname");
@@ -703,50 +652,47 @@ public class ConfigureCA {
if (external_ca.equalsIgnoreCase("true")) {
if ((req_list != null) && (dn_list != null)) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ String temp = dn_list.get(i);
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
+ ca_cert_req = req_list.get(i);
}
}
}
if (ext_ca_cert_file == null) {
- try {
- FileOutputStream fos = new FileOutputStream(
- ext_csr_file);
- PrintStream p = new PrintStream(fos);
+ try {
+ FileOutputStream fos = new FileOutputStream(ext_csr_file);
+ PrintStream p = new PrintStream( fos );
p.println(ca_cert_req);
p.close();
return true;
} catch (Exception e) {
- System.out
- .println("CertSubjectPanel: Unable to write CSR for external CA to "
- + ext_csr_file);
+ System.out.println("CertSubjectPanel: Unable to write CSR for external CA to "+ ext_csr_file);
System.out.println(e.toString());
- return false;
- }
- } else {
- try {
+ return false;
+ }
+ }
+ else {
+ try {
ca_cert_cert = "";
- FileInputStream fis = new FileInputStream(
- ext_ca_cert_file);
+ FileInputStream fis = new FileInputStream(ext_ca_cert_file);
DataInputStream in = new DataInputStream(fis);
- while (in.available() != 0) {
+ while (in.available() !=0) {
ca_cert_cert += in.readLine();
}
in.close();
-
+
signing_cc = "";
fis = new FileInputStream(ext_ca_cert_chain_file);
in = new DataInputStream(fis);
- while (in.available() != 0) {
+ while (in.available() !=0) {
signing_cc += in.readLine();
}
in.close();
return true;
- } catch (Exception e) {
- System.out
- .println("CertSubjectPanel: Unable to read in external approved CA cert or certificate chain.");
+ }
+ catch (Exception e) {
+ System.out.println("CertSubjectPanel: Unable to read in external approved CA cert or certificate chain.");
System.out.println(e.toString());
return false;
}
@@ -755,59 +701,52 @@ public class ConfigureCA {
if (req_list != null && cert_list != null && dn_list != null) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
+ String temp = dn_list.get(i);
+
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
} else if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >= 0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >=0) {
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
- // print out subject names
+
+ // print out subject names
System.out.println("ca_cert_name=" + ca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + ca_ocsp_cert_subject_name);
- System.out.println("ca_subsystem_cert_name="
- + ca_subsystem_cert_subject_name);
- System.out.println("server_cert_name="
- + ca_server_cert_subject_name);
- System.out.println("audit_signing_cert_name="
- + ca_audit_signing_cert_subject_name);
+ System.out.println(
+ "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
+ System.out.println("server_cert_name=" + ca_server_cert_subject_name);
+ System.out.println("audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
// print out requests
System.out.println("ca_cert_req=" + ca_cert_req);
System.out.println("ocsp_cert_req=" + ocsp_cert_req);
- System.out
- .println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
+ System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
System.out.println("server_cert_req=" + server_cert_req);
- System.out.println("ca_audit_siging_cert_req="
- + ca_audit_signing_cert_req);
+ System.out.println("ca_audit_siging_cert_req=" + ca_audit_signing_cert_req);
// print out certs
System.out.println("ca_cert_cert=" + ca_cert_cert);
System.out.println("ocsp_cert_cert=" + ocsp_cert_cert);
- System.out.println("ca_subsystem_cert_cert="
- + ca_subsystem_cert_cert);
+ System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert);
System.out.println("server_cert_cert=" + server_cert_cert);
- System.out.println("ca_audit_signing_cert_cert="
- + ca_audit_signing_cert_cert);
+ System.out.println("ca_audit_signing_cert_cert=" + ca_audit_signing_cert_cert);
return true;
} catch (Exception e) {
- System.out.println("Exception in CertSubjectPanel(): "
- + e.toString());
+ System.out.println("Exception in CertSubjectPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -819,26 +758,24 @@ public class ConfigureCA {
boolean st = false;
HTTPResponse hr = null;
- String query_string = "p=12" + "&op=next" + "&xml=true"
- + "&subsystem=" + URLEncoder.encode(ca_subsystem_cert_cert)
- + "&subsystem_cc=" + "&ocsp_signing="
- + URLEncoder.encode(ocsp_cert_cert) + "&ocsp_signing_cc="
- + "&signing=" + URLEncoder.encode(ca_cert_cert)
- + "&signing_cc=" + "&audit_signing="
- + URLEncoder.encode(ca_audit_signing_cert_cert)
- + "&audit_signing_cc=" + "&sslserver="
- + URLEncoder.encode(server_cert_cert) + "&sslserver_cc="
- + "";
+ String query_string = "p=12" + "&op=next" + "&xml=true" + "&subsystem="
+ + URLEncoder.encode(ca_subsystem_cert_cert) + "&subsystem_cc="
+ + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert)
+ + "&ocsp_signing_cc=" + "&signing="
+ + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
+ + "&audit_signing=" + URLEncoder.encode(ca_audit_signing_cert_cert)
+ + "&audit_signing_cc="
+ + "&sslserver=" + URLEncoder.encode(server_cert_cert)
+ + "&sslserver_cc=" + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanel()")) {
return false;
}
return true;
} catch (Exception e) {
- System.out.println("Exception in CertificatePanel(): "
- + e.toString());
+ System.out.println("Exception in CertificatePanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -857,19 +794,19 @@ public class ConfigureCA {
ArrayList<String> pp_list = null;
String genString = "...certificate be generated internally...";
- String query_string = "p=12" + "&op=apply" + "&xml=true"
- + "&subsystem=" + URLEncoder.encode(genString)
- + "&subsystem_cc=" + "&ocsp_signing="
- + URLEncoder.encode(genString) + "&ocsp_signing_cc="
- + "&signing=" + URLEncoder.encode(ca_cert_cert)
- + "&signing_cc=" + URLEncoder.encode(signing_cc)
- + "&audit_signing=" + URLEncoder.encode(genString)
- + "&audit_signing_cc=" + "&sslserver="
- + URLEncoder.encode(genString) + "&sslserver_cc=" + "";
+ String query_string = "p=12" + "&op=apply" + "&xml=true" + "&subsystem="
+ + URLEncoder.encode(genString) + "&subsystem_cc="
+ + "&ocsp_signing=" + URLEncoder.encode(genString)
+ + "&ocsp_signing_cc=" + "&signing="
+ + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
+ + URLEncoder.encode(signing_cc)
+ + "&audit_signing=" + URLEncoder.encode(genString)
+ + "&audit_signing_cc="
+ + "&sslserver=" + URLEncoder.encode(genString)
+ + "&sslserver_cc=" + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "CertificatePanelExternal()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "CertificatePanelExternal()")) {
return false;
}
@@ -887,23 +824,23 @@ public class ConfigureCA {
if (req_list != null && cert_list != null && dn_list != null) {
for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ String temp = dn_list.get(i);
if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
} else if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
} else if (temp.indexOf("auditSigningCert") >= 0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
@@ -911,35 +848,29 @@ public class ConfigureCA {
// print out subject name
System.out.println("ca_cert_name=" + ca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + ca_ocsp_cert_subject_name);
- System.out.println("ca_subsystem_cert_name="
- + ca_subsystem_cert_subject_name);
- System.out.println("server_cert_name="
- + ca_server_cert_subject_name);
- System.out.println("ca_audit_signing_cert_name="
- + ca_audit_signing_cert_subject_name);
+ System.out.println(
+ "ca_subsystem_cert_name=" + ca_subsystem_cert_subject_name);
+ System.out.println("server_cert_name=" + ca_server_cert_subject_name);
+ System.out.println(
+ "ca_audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
// print out requests
System.out.println("ca_cert_req=" + ca_cert_req);
System.out.println("ocsp_cert_req=" + ocsp_cert_req);
- System.out
- .println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
+ System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
System.out.println("server_cert_req=" + server_cert_req);
- System.out.println("ca_audit_signing_cert_req="
- + ca_audit_signing_cert_req);
+ System.out.println("ca_audit_signing_cert_req=" + ca_audit_signing_cert_req);
// print out certs
System.out.println("ca_cert_cert=" + ca_cert_cert);
System.out.println("ocsp_cert_cert=" + ocsp_cert_cert);
- System.out.println("ca_subsystem_cert_cert="
- + ca_subsystem_cert_cert);
+ System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert);
System.out.println("server_cert_cert=" + server_cert_cert);
- System.out.println("ca_audit_signing_cert_cert="
- + ca_audit_signing_cert_cert);
+ System.out.println("ca_audit_signing_cert_cert=" + ca_audit_signing_cert_cert);
return true;
} catch (Exception e) {
- System.out.println("Exception in CertificatePanelExternal(): "
- + e.toString());
+ System.out.println("Exception in CertificatePanelExternal(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -953,20 +884,17 @@ public class ConfigureCA {
if (save_p12.equalsIgnoreCase("true")) {
String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd="
- + URLEncoder.encode(backup_pwd) + "&__pwdagain="
- + URLEncoder.encode(backup_pwd);
+ + "&choice=backupkey" + "&__pwd=" + URLEncoder.encode(backup_pwd)
+ + "&__pwdagain=" + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) {
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) {
return false;
}
- query_string = "";
+ query_string = "";
- hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri,
- query_string);
+ hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
// dump hr.getResponseData() to file
@@ -977,22 +905,20 @@ public class ConfigureCA {
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod", "600", backup_fname };
+ String rtParams[] = { "chmod","600", backup_fname};
Process proc = Runtime.getRuntime().exec(rtParams);
- BufferedReader br = new BufferedReader(
- new InputStreamReader(proc.getErrorStream()));
+ BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ((line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ( (line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
// verify p12 file
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
- PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis,
- 2048));
+ PFX pfx = (PFX) pfxt.decode(new BufferedInputStream(fis, 2048));
System.out.println("Decoded PFX");
@@ -1001,8 +927,8 @@ public class ConfigureCA {
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has " + asSeq.size()
- + " SafeContents");
+ System.out.println(
+ "AuthSafes has " + asSeq.size() + " SafeContents");
fis.close();
} catch (Exception e) {
@@ -1024,16 +950,14 @@ public class ConfigureCA {
HTTPResponse hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=14&op=next&xml=true");
- if (!checkStatus(hr, "updateStatus", SUCCESS,
- "BackupContinuePanel()")) {
+ "p=14&op=next&xml=true");
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "BackupContinuePanel()")) {
return false;
}
- return true;
+ return true;
} catch (Exception e) {
- System.out.println("Exception in BackupContinuePanel(): "
- + e.toString());
+ System.out.println("Exception in BackupContinuePanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -1044,15 +968,14 @@ public class ConfigureCA {
HTTPResponse hr = null;
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=15&op=next&xml=true");
- if (!checkStatus(hr, "updateStatus", SUCCESS, "ImportCACertPanel()")) {
+ "p=15&op=next&xml=true");
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "ImportCACertPanel()")) {
return false;
}
- return true;
+ return true;
} catch (Exception e) {
- System.out.println("Exception in ImportCACertPanel(): "
- + e.toString());
+ System.out.println("Exception in ImportCACertPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -1066,9 +989,8 @@ public class ConfigureCA {
ParseXML px = new ParseXML();
String admin_cert_request = null;
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd, agent_cert_subject, agent_key_size,
- agent_key_type);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
+ agent_cert_subject, agent_key_size, agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1079,41 +1001,37 @@ public class ConfigureCA {
String crmf_request = cCrypt.generateCRMFrequest();
if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
return false;
}
admin_cert_request = crmf_request;
String query_string = "p=16" + "&op=next" + "&xml=true"
- + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
- + "&name=" + admin_user + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&profileId="
- + "caAdminCert" + "&email="
- + URLEncoder.encode(admin_email) + "&cert_request="
- + URLEncoder.encode(admin_cert_request) + "&subject="
- + URLEncoder.encode(agent_cert_subject) + "&clone=new"
- + "&import=true" + "&securitydomain="
- + URLEncoder.encode(domain_name) + "";
+ + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
+ + "&name=" + admin_user + "&__pwd=" + URLEncoder.encode(admin_password)
+ + "&__admin_password_again=" + URLEncoder.encode(admin_password) + "&profileId="
+ + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
+ + "&cert_request=" + URLEncoder.encode(admin_cert_request)
+ + "&subject=" + URLEncoder.encode(agent_cert_subject)
+ + "&clone=new"
+ + "&import=true" + "&securitydomain="
+ + URLEncoder.encode(domain_name) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "AdminCertReqPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "AdminCertReqPanel()")) {
return false;
}
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
admin_serial_number = px.getvalue("serialNumber");
return true;
} catch (Exception e) {
- System.out.println("Exception in AdminCertReqPanel(): "
- + e.toString());
+ System.out.println("Exception in AdminCertReqPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -1127,15 +1045,15 @@ public class ConfigureCA {
String cert_to_import = null;
String query_string = "&serialNumber=" + admin_serial_number
- + "&importCert=true" + "";
+ + "&importCert=true" + "";
hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string);
-
+
try {
// get response data
// Convert a byte array to base64 string
// cert_to_import = new sun.misc.BASE64Encoder().encode(
- // hr.getResponseData());
+ // hr.getResponseData());
cert_to_import = OSUtil.BtoA(hr.getResponseData());
// Convert base64 string to a byte array
@@ -1147,8 +1065,8 @@ public class ConfigureCA {
}
System.out.println("Cert to Import =" + cert_to_import);
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd, null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
+ null, null, null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1159,16 +1077,15 @@ public class ConfigureCA {
st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
+ System.out.println(
+ "ERROR: AdminCertImportPanel() during cert import");
return false;
}
System.out.println("SUCCESS: imported admin user cert");
return true;
} catch (Exception e) {
- System.out.println("Exception in AdminCertImportPanel(): "
- + e.toString());
+ System.out.println("Exception in AdminCertImportPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -1181,19 +1098,19 @@ public class ConfigureCA {
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=17" + "&op=next" + "&xml=true"
- + "&caHost=" + URLEncoder.encode("/") + "&caPort="
- + URLEncoder.encode("/") + "";
+ String query_string = "p=17" + "&op=next" + "&xml=true" + "&caHost="
+ + URLEncoder.encode("/") + "&caPort=" + URLEncoder.encode("/")
+ + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (!checkStatus(hr, "updateStatus", SUCCESS, "UpdateDomainPanel()")) {
+ if (! checkStatus(hr, "updateStatus", SUCCESS, "UpdateDomainPanel()")) {
return false;
}
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
-
+
String caHost = px.getvalue("host");
String caPort = px.getvalue("port");
String systemType = px.getvalue("systemType");
@@ -1201,11 +1118,10 @@ public class ConfigureCA {
System.out.println("caHost=" + caHost);
System.out.println("caPort=" + caPort);
System.out.println("systemType=" + systemType);
-
+
return true;
} catch (Exception e) {
- System.out.println("Exception in UpdateDomainPanel(): "
- + e.toString());
+ System.out.println("Exception in UpdateDomainPanel(): " + e.toString());
e.printStackTrace();
return false;
}
@@ -1242,8 +1158,7 @@ public class ConfigureCA {
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out
- .println("ERROR: ConfigureCA: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureCA: TokenChoicePanel() failure");
return false;
}
@@ -1258,16 +1173,15 @@ public class ConfigureCA {
// 4. display cert chain panel and security domain login
if (clone) {
boolean disp_st = DisplayCertChainPanel();
- if (!disp_st) {
- System.out
- .println("ERROR: ConfigureCA: DisplayCertChainPanel() failure");
+ if(!disp_st) {
+ System.out.println("ERROR: ConfigureCA: DisplayCertChainPanel() failure");
return false;
}
boolean sd_st = SecurityDomainLoginPanel();
- if (!sd_st) {
- System.out
- .println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
+ if(! sd_st)
+ {
+ System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
return false;
}
@@ -1285,19 +1199,17 @@ public class ConfigureCA {
if (clone) {
boolean restore_st = RestoreKeyCertPanel();
if (!restore_st) {
- System.out
- .println("ERROR: ConfigureCA: RestoreKeyCertPanel() failure");
+ System.out.println("ERROR: ConfigureCA: RestoreKeyCertPanel() failure");
return false;
}
}
// 7. hierarchy panel
- if (!clone) {
+ if (! clone) {
boolean disp_h = HierarchyPanel();
if (!disp_h) {
- System.out
- .println("ERROR: ConfigureCA: HierarchyPanel() failure");
+ System.out.println("ERROR: ConfigureCA: HierarchyPanel() failure");
return false;
}
}
@@ -1306,8 +1218,8 @@ public class ConfigureCA {
boolean disp_ldap = LdapConnectionPanel();
if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureCA: LdapConnectionPanel() failure");
+ System.out.println(
+ "ERROR: ConfigureCA: LdapConnectionPanel() failure");
return false;
}
@@ -1323,8 +1235,7 @@ public class ConfigureCA {
boolean disp_csubj = CertSubjectPanel();
if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureCA: CertSubjectPanel() failure");
+ System.out.println("ERROR: ConfigureCA: CertSubjectPanel() failure");
return false;
}
@@ -1337,26 +1248,22 @@ public class ConfigureCA {
disp_cp = CertificatePanelExternal();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureCA: CertificatePanelExternal() failure");
+ System.out.println("ERROR: ConfigureCA: CertificatePanelExternal() failure");
return false;
}
- } else {
- // first pass - cacert file not defined
- System.out
- .println("A Certificate Request has been generated and stored in "
- + ext_csr_file);
- System.out
- .println("Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain");
- return true;
+ }
+ else {
+ // first pass - cacert file not defined
+ System.out.println("A Certificate Request has been generated and stored in " + ext_csr_file);
+ System.out.println("Please submit this CSR to your external CA and obtain the CA Cert and CA Cert Chain");
+ return true;
}
}
disp_cp = CertificatePanel();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureCA: CertificatePanel() failure");
+ System.out.println("ERROR: ConfigureCA: CertificatePanel() failure");
return false;
}
@@ -1372,31 +1279,30 @@ public class ConfigureCA {
boolean disp_back_cont = BackupContinuePanel();
if (!disp_back_cont) {
- System.out
- .println("ERROR: ConfigureCA: BackupContinuePanel() failure");
+ System.out.println("ERROR: ConfigureCA: BackupContinuePanel() failure");
return false;
}
+
// 15. Import CA Cert panel
boolean disp_import_cacert = ImportCACertPanel();
if (!disp_import_cacert) {
- System.out
- .println("ERROR: ConfigureCA: ImportCACertPanel() failure");
+ System.out.println("ERROR: ConfigureCA: ImportCACertPanel() failure");
return false;
}
-
- if (clone) {
+
+ if (clone) {
// no other panels required for clone
return true;
}
+
// 16. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureCA: AdminCertReqPanel() failure");
+ System.out.println("ERROR: ConfigureCA: AdminCertReqPanel() failure");
return false;
}
@@ -1404,8 +1310,8 @@ public class ConfigureCA {
boolean disp_im = AdminCertImportPanel();
if (!disp_im) {
- System.out
- .println("ERROR: ConfigureCA: AdminCertImportPanel() failure");
+ System.out.println(
+ "ERROR: ConfigureCA: AdminCertImportPanel() failure");
return false;
}
@@ -1413,8 +1319,7 @@ public class ConfigureCA {
boolean disp_ud = UpdateDomainPanel();
if (!disp_ud) {
- System.out
- .println("ERROR: ConfigureCA: UpdateDomainPanel() failure");
+ System.out.println("ERROR: ConfigureCA: UpdateDomainPanel() failure");
return false;
}
@@ -1445,7 +1350,7 @@ public class ConfigureCA {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1474,7 +1379,7 @@ public class ConfigureCA {
StringHolder x_ocsp_signing_key_type = new StringHolder();
StringHolder x_ocsp_signing_key_curvename = new StringHolder();
StringHolder x_ocsp_signing_signingalgorithm = new StringHolder();
-
+
// key properties (custom - audit_signing)
StringHolder x_audit_signing_key_size = new StringHolder();
StringHolder x_audit_signing_key_type = new StringHolder();
@@ -1516,17 +1421,17 @@ public class ConfigureCA {
// external CA cert
StringHolder x_external_ca = new StringHolder();
- StringHolder x_ext_ca_cert_file = new StringHolder();
- StringHolder x_ext_ca_cert_chain_file = new StringHolder();
- StringHolder x_ext_csr_file = new StringHolder();
+ StringHolder x_ext_ca_cert_file = new StringHolder();
+ StringHolder x_ext_ca_cert_chain_file = new StringHolder();
+ StringHolder x_ext_csr_file = new StringHolder();
- // clone parameters
+ //clone parameters
StringHolder x_clone = new StringHolder();
StringHolder x_clone_uri = new StringHolder();
StringHolder x_clone_p12_file = new StringHolder();
StringHolder x_clone_p12_passwd = new StringHolder();
- // security domain
+ //security domain
StringHolder x_sd_hostname = new StringHolder();
StringHolder x_sd_ssl_port = new StringHolder();
StringHolder x_sd_agent_port = new StringHolder();
@@ -1534,204 +1439,124 @@ public class ConfigureCA {
StringHolder x_sd_admin_name = new StringHolder();
StringHolder x_sd_admin_password = new StringHolder();
+
// parse the args
ArgParser parser = new ArgParser("ConfigureCA");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
+ parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
+ parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
+ x_client_certdb_dir);
parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
+ x_client_certdb_pwd);
+ parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
+ parser.addOption("-domain_name %s #domain name", x_domain_name);
+ parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
+ parser.addOption("-admin_email %s #Admin email", x_admin_email);
+ parser.addOption("-admin_password %s #Admin password", x_admin_password);
+ parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
parser.addOption("-agent_key_size %s #Agent Cert Key size",
- x_agent_key_size);
+ x_agent_key_size);
parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
+ x_agent_key_type);
parser.addOption("-agent_cert_subject %s #Agent Certificate Subject",
- x_agent_cert_subject);
+ x_agent_cert_subject);
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
+ parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
+ parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
+ parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption(
- "-secure_conn %s #use ldaps port (optional, default is false)",
- x_secure_conn);
- parser.addOption(
- "-remove_data %s #remove existing data under base_dn (optional, default is false) ",
- x_remove_data);
- parser.addOption(
- "-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)",
- x_clone_start_tls);
+ x_bind_password);
+ parser.addOption("-base_dn %s #base dn", x_base_dn);
+ parser.addOption("-db_name %s #db name", x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption(
- "-key_type %s #Key type [RSA,ECC] (optional, default is RSA)",
- x_key_type);
- parser.addOption(
- "-key_size %s #Key Size (optional, for RSA default is 2048)",
- x_key_size);
- parser.addOption(
- "-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)",
- x_key_curvename);
- parser.addOption(
- "-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)",
- x_key_algorithm);
- parser.addOption(
- "-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)",
- x_signing_algorithm);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_key_algorithm);
+ parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", x_signing_algorithm);
// key and algorithm options for signing certificate (overrides default)
- parser.addOption(
- "-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_signing_key_type);
- parser.addOption(
- "-signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_signing_key_size);
- parser.addOption(
- "-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_signing_key_curvename);
- parser.addOption(
- "-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)",
- x_signing_signingalgorithm);
-
- // key and algorithm options for ocsp_signing certificate (overrides
- // default)
- parser.addOption(
- "-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_ocsp_signing_key_type);
- parser.addOption(
- "-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_ocsp_signing_key_size);
- parser.addOption(
- "-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_ocsp_signing_key_curvename);
- parser.addOption(
- "-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)",
- x_ocsp_signing_signingalgorithm);
-
- // key and algorithm options for audit_signing certificate (overrides
- // default)
- parser.addOption(
- "-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_audit_signing_key_type);
- parser.addOption(
- "-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_audit_signing_key_size);
- parser.addOption(
- "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides
- // default)
- parser.addOption(
- "-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_subsystem_key_type);
- parser.addOption(
- "-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_subsystem_key_size);
- parser.addOption(
- "-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides
- // default)
- parser.addOption(
- "-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_sslserver_key_type);
- parser.addOption(
- "-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_sslserver_key_size);
- parser.addOption(
- "-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_sslserver_key_curvename);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional - only required for HSM)",
- x_token_pwd);
+ parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
+ parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
+ parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
+ parser.addOption("-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
+
+ // key and algorithm options for ocsp_signing certificate (overrides default)
+ parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
+ parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
+ parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
+ parser.addOption("-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", x_ocsp_signing_signingalgorithm);
+
+ // key and algorithm options for audit_signing certificate (overrides default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption("-token_name %s #HSM/Software Token name", x_token_name);
+ parser.addOption("-token_pwd %s #HSM/Software Token password (optional - only required for HSM)",
+ x_token_pwd);
parser.addOption("-save_p12 %s #Enable/Disable p12 Export[true,false]",
- x_save_p12);
- parser.addOption(
- "-backup_pwd %s #Backup Password for p12 (optional, only required if -save_p12 = true)",
- x_backup_pwd);
- parser.addOption(
- "-backup_fname %s #Backup File for p12, (optional, default is /root/tmp-ca.p12)",
- x_backup_fname);
+ x_save_p12);
+ parser.addOption("-backup_pwd %s #Backup Password for p12 (optional, only required if -save_p12 = true)", x_backup_pwd);
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default is /root/tmp-ca.p12)", x_backup_fname);
parser.addOption("-ca_sign_cert_subject_name %s #CA cert subject name",
x_ca_sign_cert_subject_name);
parser.addOption(
"-ca_subsystem_cert_subject_name %s #CA subsystem cert subject name",
- x_ca_subsystem_cert_subject_name);
+ x_ca_subsystem_cert_subject_name);
parser.addOption(
"-ca_ocsp_cert_subject_name %s #CA ocsp cert subject name",
- x_ca_ocsp_cert_subject_name);
+ x_ca_ocsp_cert_subject_name);
parser.addOption(
"-ca_server_cert_subject_name %s #CA server cert subject name",
- x_ca_server_cert_subject_name);
+ x_ca_server_cert_subject_name);
parser.addOption(
"-ca_audit_signing_cert_subject_name %s #CA audit signing cert subject name",
- x_ca_audit_signing_cert_subject_name);
+ x_ca_audit_signing_cert_subject_name);
parser.addOption("-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
- parser.addOption(
- "-external %s #Subordinate to external CA [true,false] (optional, default false)",
- x_external_ca);
- parser.addOption(
- "-ext_ca_cert_file %s #File with CA cert from external CA (optional)",
- x_ext_ca_cert_file);
- parser.addOption(
- "-ext_ca_cert_chain_file %s #File with CA cert from external CA (optional)",
+ x_subsystem_name);
+
+ parser.addOption("-external %s #Subordinate to external CA [true,false] (optional, default false)",
+ x_external_ca);
+ parser.addOption("-ext_ca_cert_file %s #File with CA cert from external CA (optional)",
+ x_ext_ca_cert_file);
+ parser.addOption("-ext_ca_cert_chain_file %s #File with CA cert from external CA (optional)",
x_ext_ca_cert_chain_file);
- parser.addOption(
- "-ext_csr_file %s #File to save the CSR for submission to an external CA (optional)",
+ parser.addOption("-ext_csr_file %s #File to save the CSR for submission to an external CA (optional)",
x_ext_csr_file);
- parser.addOption(
- "-clone %s #Clone of another CA [true, false] (optional, default false)",
- x_clone);
- parser.addOption(
- "-clone_uri %s #URL of Master CA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)",
- x_clone_uri);
- parser.addOption(
- "-clone_p12_file %s #File containing pk12 keys of Master CA (optional, required if -clone=true)",
- x_clone_p12_file);
- parser.addOption(
- "-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)",
- x_clone_p12_passwd);
+ parser.addOption("-clone %s #Clone of another CA [true, false] (optional, default false)", x_clone);
+ parser.addOption("-clone_uri %s #URL of Master CA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)", x_clone_uri);
+ parser.addOption("-clone_p12_file %s #File containing pk12 keys of Master CA (optional, required if -clone=true)", x_clone_p12_file);
+ parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", x_clone_p12_passwd);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname (optional, required if -clone=true)", x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port (optional, required if -clone=true)", x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port (optional, required if -clone=true)", x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port (optional, required if -clone=true)", x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain admin name (optional, required if -clone=true)",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain admin password (optional, required if -clone=true)",
+ x_sd_admin_password);
- parser.addOption(
- "-sd_hostname %s #Security Domain Hostname (optional, required if -clone=true)",
- x_sd_hostname);
- parser.addOption(
- "-sd_ssl_port %s #Security Domain SSL EE port (optional, required if -clone=true)",
- x_sd_ssl_port);
- parser.addOption(
- "-sd_agent_port %s #Security Domain SSL Agent port (optional, required if -clone=true)",
- x_sd_agent_port);
- parser.addOption(
- "-sd_admin_port %s #Security Domain SSL Admin port (optional, required if -clone=true)",
- x_sd_admin_port);
- parser.addOption(
- "-sd_admin_name %s #Security Domain admin name (optional, required if -clone=true)",
- x_sd_admin_name);
- parser.addOption(
- "-sd_admin_password %s #Security Domain admin password (optional, required if -clone=true)",
- x_sd_admin_password);
// and then match the arguments
String[] unmatched = null;
@@ -1769,50 +1594,35 @@ public class ConfigureCA {
key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE);
signing_key_type = set_default(x_signing_key_type.value, key_type);
- ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value,
- key_type);
- audit_signing_key_type = set_default(x_audit_signing_key_type.value,
- key_type);
+ ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value, key_type);
+ audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type);
subsystem_key_type = set_default(x_subsystem_key_type.value, key_type);
sslserver_key_type = set_default(x_sslserver_key_type.value, key_type);
key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE);
signing_key_size = set_default(x_signing_key_size.value, key_size);
- ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value,
- key_size);
- audit_signing_key_size = set_default(x_audit_signing_key_size.value,
- key_size);
+ ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value, key_size);
+ audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size);
subsystem_key_size = set_default(x_subsystem_key_size.value, key_size);
sslserver_key_size = set_default(x_sslserver_key_size.value, key_size);
- key_curvename = set_default(x_key_curvename.value,
- DEFAULT_KEY_CURVENAME);
- signing_key_curvename = set_default(x_signing_key_curvename.value,
- key_curvename);
- ocsp_signing_key_curvename = set_default(
- x_ocsp_signing_key_curvename.value, key_curvename);
- audit_signing_key_curvename = set_default(
- x_audit_signing_key_curvename.value, key_curvename);
- subsystem_key_curvename = set_default(x_subsystem_key_curvename.value,
- key_curvename);
- sslserver_key_curvename = set_default(x_sslserver_key_curvename.value,
- key_curvename);
+ key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME);
+ signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename);
+ ocsp_signing_key_curvename = set_default(x_ocsp_signing_key_curvename.value, key_curvename);
+ audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename);
+ subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename);
+ sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename);
if (signing_key_type.equalsIgnoreCase("RSA")) {
- key_algorithm = set_default(x_key_algorithm.value,
- DEFAULT_KEY_ALGORITHM_RSA);
+ key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA);
} else {
- key_algorithm = set_default(x_key_algorithm.value,
- DEFAULT_KEY_ALGORITHM_ECC);
+ key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC);
}
-
- signing_algorithm = set_default(x_signing_algorithm.value,
- key_algorithm);
- signing_signingalgorithm = set_default(
- x_signing_signingalgorithm.value, signing_algorithm);
- ocsp_signing_signingalgorithm = set_default(
- x_ocsp_signing_signingalgorithm.value, signing_algorithm);
-
+
+ signing_algorithm = set_default(x_signing_algorithm.value, key_algorithm);
+ signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm);
+ ocsp_signing_signingalgorithm = set_default(x_ocsp_signing_signingalgorithm.value, signing_algorithm);
+
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
save_p12 = x_save_p12.value;
@@ -1828,9 +1638,9 @@ public class ConfigureCA {
ca_ocsp_cert_subject_name = x_ca_ocsp_cert_subject_name.value;
ca_server_cert_subject_name = x_ca_server_cert_subject_name.value;
ca_audit_signing_cert_subject_name = x_ca_audit_signing_cert_subject_name.value;
-
+
subsystem_name = x_subsystem_name.value;
-
+
external_ca = set_default(x_external_ca.value, "false");
ext_ca_cert_file = x_ext_ca_cert_file.value;
ext_ca_cert_chain_file = x_ext_ca_cert_chain_file.value;
@@ -1853,15 +1663,18 @@ public class ConfigureCA {
sd_admin_password = x_sd_admin_password.value;
boolean st = ca.ConfigureCAInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create CA");
System.exit(-1);
}
-
+
System.out.println("Certificate System - CA Instance Configured.");
System.exit(0);
-
+
}
-};
+}
+
+
+;
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
index f8df962a..c79ec4ed 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,7 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -39,7 +39,8 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureDRM {
+public class ConfigureDRM
+{
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
@@ -51,7 +52,7 @@ public class ConfigureDRM {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/kra/admin/console/config/login";
public static String wizard_uri = "/kra/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -77,7 +78,7 @@ public class ConfigureDRM {
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -159,13 +160,14 @@ public class ConfigureDRM {
public static String backup_pwd = null;
public static String backup_fname = null;
- // cert subject names
+ // cert subject names
public static String drm_transport_cert_subject_name = null;
public static String drm_subsystem_cert_subject_name = null;
public static String drm_storage_cert_subject_name = null;
public static String drm_server_cert_subject_name = null;
public static String drm_audit_signing_cert_subject_name = null;
+
public static String subsystem_name = null;
// cloning
@@ -174,32 +176,38 @@ public class ConfigureDRM {
public static String clone_p12_passwd = null;
public static String clone_p12_file = null;
- // for correct selection of CA to be cloned
+ //for correct selection of CA to be cloned
public static String urls;
-
- public ConfigureDRM() {
+
+ public ConfigureDRM ()
+ {
// do nothing :)
}
- public void sleep_time() {
- try {
+ public void sleep_time()
+ {
+ try
+ {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- } catch (Exception e) {
+ }
+ catch(Exception e)
+ {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel() {
+ public boolean LoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -207,15 +215,14 @@ public class ConfigureDRM {
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp != null) {
+ if (temp!=null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
+ HTTPClient.j_session_id = temp.substring(0,index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri, "p=0&op=next&xml=true");
// parse xml here
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -225,7 +232,8 @@ public class ConfigureDRM {
return st;
}
- public boolean TokenChoicePanel() {
+ public boolean TokenChoicePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -235,9 +243,10 @@ public class ConfigureDRM {
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token");
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode("Internal Key Storage Token");
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -245,20 +254,23 @@ public class ConfigureDRM {
px.prettyprintxml();
} else {
// login to hsm first
- query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=2" + "&op=next" + "&xml=true" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode(token_name);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -269,18 +281,24 @@ public class ConfigureDRM {
return true;
}
- public boolean DomainPanel() {
+ public boolean DomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
- String query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&choice=existingdomain"+
+ "&p=3" +
+ "&op=next" +
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -291,41 +309,43 @@ public class ConfigureDRM {
}
- public boolean DisplayChainPanel() {
+ public boolean DisplayChainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
return true;
}
- public boolean SecurityDomainLoginPanel() {
+ public boolean SecurityDomainLoginPanel()
+ {
try {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String kra_url = "https://" + cs_hostname + ":" + cs_port
- + "/kra/admin/console/config/wizard" + "?p=5&subsystem=KRA";
+ String kra_url = "https://" + cs_hostname + ":" + cs_port +
+ "/kra/admin/console/config/wizard" +
+ "?p=5&subsystem=KRA" ;
- String query_string = "url=" + URLEncoder.encode(kra_url);
+ String query_string = "url=" + URLEncoder.encode(kra_url);
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(kra_url);
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(kra_url) ;
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
// get session id from security domain
@@ -337,10 +357,13 @@ public class ConfigureDRM {
// use session id to connect back to KRA
- String query_string_2 = "p=5" + "&subsystem=KRA" + "&session_id="
- + kra_session_id + "&xml=true";
+ String query_string_2 = "p=5" +
+ "&subsystem=KRA" +
+ "&session_id=" + kra_session_id +
+ "&xml=true" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
if (clone) {
// parse urls
@@ -349,7 +372,7 @@ public class ConfigureDRM {
if (indx < 0) {
throw new Exception("Invalid clone_uri");
}
- urls = urls.substring(urls.lastIndexOf("<option", indx), indx);
+ urls = urls.substring(urls.lastIndexOf("<option" , indx), indx);
urls = urls.split("\"")[1];
System.out.println("urls =" + urls);
@@ -357,14 +380,14 @@ public class ConfigureDRM {
return true;
} catch (Exception e) {
- System.out.println("Exception in SecurityDomainLoginPanel(): "
- + e.toString());
+ System.out.println("Exception in SecurityDomainLoginPanel(): " + e.toString());
e.printStackTrace();
return false;
}
}
-
- public boolean SubsystemPanel() {
+
+ public boolean SubsystemPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -372,15 +395,16 @@ public class ConfigureDRM {
String query_string = null;
if (!clone) {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=newsubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name);
+ + "&choice=newsubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name);
} else {
query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=clonesubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name) + "&urls=" + urls;
+ + "&choice=clonesubsystem" + "&subsystemName="
+ + URLEncoder.encode(subsystem_name)
+ + "&urls=" + urls;
}
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -396,8 +420,8 @@ public class ConfigureDRM {
ParseXML px = new ParseXML();
String query_string = "p=6" + "&op=next" + "&xml=true"
- + "&__password=" + URLEncoder.encode(clone_p12_passwd)
- + "&path=" + URLEncoder.encode(clone_p12_file) + "";
+ + "&__password=" + URLEncoder.encode(clone_p12_passwd)
+ + "&path=" + URLEncoder.encode(clone_p12_file) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
@@ -407,32 +431,33 @@ public class ConfigureDRM {
px.prettyprintxml();
return true;
} catch (Exception e) {
- System.out.println("Exception in RestoreKeyCertPanel(): "
- + e.toString());
+ System.out.println("Exception in RestoreKeyCertPanel(): " + e.toString());
e.printStackTrace();
return false;
}
}
- public boolean LdapConnectionPanel() {
+ public boolean LdapConnectionPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=7" + "&op=next" + "&xml=true" + "&host="
- + URLEncoder.encode(ldap_host) + "&port="
- + URLEncoder.encode(ldap_port) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true") ? "&secureConn=on" : "")
- + (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "")
- + (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=7" + "&op=next" + "&xml=true" +
+ "&host=" + URLEncoder.encode(ldap_host) +
+ "&port=" + URLEncoder.encode(ldap_port) +
+ "&binddn=" + URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" + URLEncoder.encode(bind_password) +
+ "&basedn=" + URLEncoder.encode(base_dn) +
+ "&database=" + URLEncoder.encode(db_name) +
+ "&display=" + URLEncoder.encode("$displayStr") +
+ (secure_conn.equals("true")? "&secureConn=on": "") +
+ (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
+ (remove_data.equals("true")? "&removeData=true": "");
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -442,7 +467,8 @@ public class ConfigureDRM {
return true;
}
- public boolean KeyPanel() {
+ public boolean KeyPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -452,74 +478,56 @@ public class ConfigureDRM {
String query_string = null;
if (!clone) {
- query_string = "p=8" + "&op=next" + "&xml=true"
- + "&transport_custom_size="
- + transport_key_size
- + "&storage_custom_size="
- + storage_key_size
- + "&subsystem_custom_size="
- + subsystem_key_size
- + "&sslserver_custom_size="
- + sslserver_key_size
- + "&audit_signing_custom_size="
- + key_size
- + "&custom_size="
- + key_size
- + "&transport_custom_curvename="
- + transport_key_curvename
- + "&storage_custom_curvename="
- + storage_key_curvename
- + "&subsystem_custom_curvename="
- + subsystem_key_curvename
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename
- + "&audit_signing_custom_curvename="
- + audit_signing_key_curvename
- + "&custom_curvename="
- + key_curvename
- + "&transport_keytype="
- + transport_key_type
- + "&storage_keytype="
- + storage_key_type
- + "&subsystem_keytype="
- + subsystem_key_type
- + "&sslserver_keytype="
- + sslserver_key_type
- + "&audit_signing_keytype="
- + audit_signing_key_type
- + "&keytype="
- + key_type
- + "&transport_choice=custom"
- + "&storage_choice=custom"
- + "&subsystem_choice=custom"
- + "&sslserver_choice=custom"
- + "&choice=custom"
- + "&audit_signing_choice=custom"
- + "&signingalgorithm="
- + signing_algorithm
- + "&transport_signingalgorithm="
- + transport_signingalgorithm;
+ query_string = "p=8" + "&op=next" + "&xml=true" +
+ "&transport_custom_size=" + transport_key_size +
+ "&storage_custom_size=" + storage_key_size +
+ "&subsystem_custom_size=" + subsystem_key_size +
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&audit_signing_custom_size=" + key_size +
+ "&custom_size=" + key_size +
+ "&transport_custom_curvename=" + transport_key_curvename +
+ "&storage_custom_curvename=" + storage_key_curvename +
+ "&subsystem_custom_curvename=" + subsystem_key_curvename +
+ "&sslserver_custom_curvename=" + sslserver_key_curvename +
+ "&audit_signing_custom_curvename=" + audit_signing_key_curvename +
+ "&custom_curvename=" + key_curvename +
+ "&transport_keytype=" + transport_key_type +
+ "&storage_keytype=" + storage_key_type +
+ "&subsystem_keytype=" + subsystem_key_type +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&audit_signing_keytype=" + audit_signing_key_type +
+ "&keytype=" + key_type +
+ "&transport_choice=custom"+
+ "&storage_choice=custom"+
+ "&subsystem_choice=custom"+
+ "&sslserver_choice=custom"+
+ "&choice=custom"+
+ "&audit_signing_choice=custom" +
+ "&signingalgorithm=" + signing_algorithm +
+ "&transport_signingalgorithm=" + transport_signingalgorithm;
} else {
- query_string = "p=8" + "&op=next" + "&xml=true"
- + "&sslserver_custom_size=" + sslserver_key_size
- + "&sslserver_keytype=" + sslserver_key_type
- + "&sslserver_choice=custom" + "&custom_size=" + key_size
- + "&keytype=" + key_type + "&choice=custom";
- }
+ query_string = "p=8" + "&op=next" + "&xml=true" +
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&sslserver_choice=custom" +
+ "&custom_size=" + key_size +
+ "&keytype=" + key_type +
+ "&choice=custom";
+ }
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair", "DN");
+
+ al = px.constructValueList("CertReqPair","DN");
// get ca cert subject name
if (al != null) {
- for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
+ for (int i=0; i < al.size(); i++) {
+ String temp = al.get(i);
if (temp.indexOf("DRM Transport") > 0) {
drm_transport_cert_name = temp;
} else if (temp.indexOf("DRM Storage") > 0) {
@@ -533,21 +541,23 @@ public class ConfigureDRM {
}
}
}
-
- System.out.println("default: drm_transport_cert_name="
- + drm_transport_cert_name);
- System.out.println("default: drm_storage_cert_name="
- + drm_storage_cert_name);
- System.out.println("default: drm_subsystem_cert_name="
- + drm_subsystem_cert_name);
- System.out.println("default: drm_audit_signing_cert_name="
- + drm_audit_signing_cert_name);
-
- System.out.println("default: server_cert_name=" + server_cert_name);
+
+ System.out.println("default: drm_transport_cert_name=" +
+ drm_transport_cert_name);
+ System.out.println("default: drm_storage_cert_name=" +
+ drm_storage_cert_name);
+ System.out.println("default: drm_subsystem_cert_name=" +
+ drm_subsystem_cert_name);
+ System.out.println("default: drm_audit_signing_cert_name=" +
+ drm_audit_signing_cert_name);
+
+ System.out.println("default: server_cert_name=" +
+ server_cert_name);
return true;
}
- public boolean CertSubjectPanel() {
+ public boolean CertSubjectPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -557,64 +567,69 @@ public class ConfigureDRM {
ArrayList<String> dn_list = null;
String query_string = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
if (!clone) {
- query_string = "p=9" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(drm_subsystem_cert_subject_name)
- + "&transport="
- + URLEncoder.encode(drm_transport_cert_subject_name)
- + "&storage="
- + URLEncoder.encode(drm_storage_cert_subject_name)
- + "&sslserver="
- + URLEncoder.encode(drm_server_cert_subject_name)
- + "&audit_signing="
- + URLEncoder.encode(drm_audit_signing_cert_subject_name)
- + "&urls=" + URLEncoder.encode(domain_url);
+ query_string = "p=9" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(drm_subsystem_cert_subject_name) +
+ "&transport=" +
+ URLEncoder.encode(drm_transport_cert_subject_name) +
+ "&storage=" +
+ URLEncoder.encode(drm_storage_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(drm_server_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(drm_audit_signing_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url);
} else {
- query_string = "p=9" + "&op=next" + "&xml=true" + "&sslserver="
- + URLEncoder.encode(drm_server_cert_subject_name)
- + "&urls=" + URLEncoder.encode(domain_url);
+ query_string = "p=9" + "&op=next" + "&xml=true" +
+ "&sslserver=" +
+ URLEncoder.encode(drm_server_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url);
}
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair", "Request");
- cert_list = px.constructValueList("CertReqPair", "Certificate");
- dn_list = px.constructValueList("CertReqPair", "Nickname");
+
+ req_list = px.constructValueList("CertReqPair","Request");
+ cert_list = px.constructValueList("CertReqPair","Certificate");
+ dn_list = px.constructValueList("CertReqPair","Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
+ for (int i=0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
if (temp.indexOf("transportCert") >= 0) {
- drm_transport_cert_req = req_list.get(i);
- drm_transport_cert_cert = cert_list.get(i);
+ drm_transport_cert_req = req_list.get(i);
+ drm_transport_cert_cert = cert_list.get(i);
} else if (temp.indexOf("storageCert") >= 0) {
- drm_storage_cert_req = req_list.get(i);
- drm_storage_cert_cert = cert_list.get(i);
+ drm_storage_cert_req = req_list.get(i);
+ drm_storage_cert_cert = cert_list.get(i);
} else if (temp.indexOf("subsystemCert") >= 0) {
- drm_subsystem_cert_req = req_list.get(i);
- drm_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >= 0) {
- drm_audit_signing_cert_req = req_list.get(i);
- drm_audit_signing_cert_cert = cert_list.get(i);
+ drm_subsystem_cert_req = req_list.get(i);
+ drm_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >=0) {
+ drm_audit_signing_cert_req = req_list.get(i);
+ drm_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel() {
+ public boolean CertificatePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -624,56 +639,68 @@ public class ConfigureDRM {
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
- String query_string = "p=10" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(drm_subsystem_cert_cert) + "&subsystem_cc="
- + "&transport=" + URLEncoder.encode(drm_transport_cert_cert)
- + "&transport_cc=" + "&storage="
- + URLEncoder.encode(drm_storage_cert_cert) + "&storage_cc="
- + "&sslserver=" + URLEncoder.encode(server_cert_cert)
- + "&sslserver_cc=" + "&audit_signing="
- + URLEncoder.encode(drm_audit_signing_cert_cert)
- + "&audit_signing_cc=";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=10" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(drm_subsystem_cert_cert) +
+ "&subsystem_cc=" +
+ "&transport=" +
+ URLEncoder.encode(drm_transport_cert_cert) +
+ "&transport_cc=" +
+ "&storage=" +
+ URLEncoder.encode(drm_storage_cert_cert) +
+ "&storage_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&audit_signing=" +
+ URLEncoder.encode(drm_audit_signing_cert_cert) +
+ "&audit_signing_cc=";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel() {
+ public boolean BackupPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=11" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd="
- + URLEncoder.encode(backup_pwd) + "&__pwdagain="
- + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=11" + "&op=next" + "&xml=true" +
+ "&choice=backupkey" +
+ "&__pwd=" + URLEncoder.encode(backup_pwd) +
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel() {
+ public boolean SavePKCS12Panel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "";
- hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
+ String query_string = "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
// dump hr.getResponseData() to file
try {
@@ -682,18 +709,17 @@ public class ConfigureDRM {
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod", "600", backup_fname };
+ String rtParams[] = { "chmod","600", backup_fname};
Process proc = Runtime.getRuntime().exec(rtParams);
- BufferedReader br = new BufferedReader(new InputStreamReader(
- proc.getErrorStream()));
+ BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ((line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ( (line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -701,18 +727,17 @@ public class ConfigureDRM {
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: " + pfx.getVersion());
+ System.out.println("Version: "+pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has " + asSeq.size()
- + " SafeContents");
+ System.out.println("AuthSafes has "+
+ asSeq.size()+" SafeContents");
fis.close();
if (clone) {
query_string = "p=12" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -727,15 +752,19 @@ public class ConfigureDRM {
return true;
}
- public boolean AdminCertReqPanel() {
+ public boolean AdminCertReqPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.setTransportCert(null);
@@ -745,67 +774,76 @@ public class ConfigureDRM {
String crmf_request = cCrypt.generateCRMFrequest();
if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
}
admin_cert_request = crmf_request;
- String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
- + "&name=" + admin_user + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&profileId="
- + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
- + "&cert_request=" + URLEncoder.encode(admin_cert_request)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&clone=new" + "&import=true" + "&securitydomain="
- + URLEncoder.encode(domain_name);
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=13" + "&op=next" + "&xml=true" +
+ "&cert_request_type=" + "crmf" +
+ "&uid=" + admin_user +
+ "&name=" + admin_user +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&profileId=" + "caAdminCert" +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&clone=new" +
+ "&import=true" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel() {
+ public boolean AdminCertImportPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true";
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
+
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import = OSUtil.BtoA(hr.getResponseData());
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -813,30 +851,35 @@ public class ConfigureDRM {
return true;
}
- public boolean UpdateDomainPanel() {
+ public boolean UpdateDomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=14" + "&op=next" + "&xml=true" + "&caHost="
- + URLEncoder.encode(sd_hostname) + "&caPort="
- + URLEncoder.encode(sd_agent_port);
+ String query_string = "p=14" + "&op=next" + "&xml=true" +
+ "&caHost=" + URLEncoder.encode(sd_hostname) +
+ "&caPort=" + URLEncoder.encode(sd_agent_port);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean ConfigureDRMInstance() {
+ public boolean ConfigureDRMInstance()
+ {
// 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
@@ -855,8 +898,7 @@ public class ConfigureDRM {
// 2. Token Choice Panel
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out
- .println("ERROR: ConfigureDRM: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureDRM: TokenChoicePanel() failure");
return false;
}
@@ -872,8 +914,7 @@ public class ConfigureDRM {
// 4. display cert chain panel
boolean disp_st = DisplayChainPanel();
if (!disp_st) {
- System.out
- .println("ERROR: ConfigureDRM: DisplayChainPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: DisplayChainPanel() failure");
return false;
}
@@ -881,8 +922,7 @@ public class ConfigureDRM {
// security domain login panel
boolean disp_sd = SecurityDomainLoginPanel();
if (!disp_sd) {
- System.out
- .println("ERROR: ConfigureDRM: SecurityDomainLoginPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: SecurityDomainLoginPanel() failure");
return false;
}
@@ -899,8 +939,7 @@ public class ConfigureDRM {
if (clone) {
boolean restore_st = RestoreKeyCertPanel();
if (!restore_st) {
- System.out
- .println("ERROR: ConfigureCA: RestoreKeyCertPanel() failure");
+ System.out.println("ERROR: ConfigureCA: RestoreKeyCertPanel() failure");
return false;
}
}
@@ -909,8 +948,7 @@ public class ConfigureDRM {
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureDRM: LdapConnectionPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: LdapConnectionPanel() failure");
return false;
}
@@ -927,8 +965,7 @@ public class ConfigureDRM {
// 10. Cert Subject Panel
boolean disp_csubj = CertSubjectPanel();
if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureDRM: CertSubjectPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: CertSubjectPanel() failure");
return false;
}
@@ -936,8 +973,7 @@ public class ConfigureDRM {
// 11. Certificate Panel
boolean disp_cp = CertificatePanel();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureDRM: CertificatePanel() failure");
+ System.out.println("ERROR: ConfigureDRM: CertificatePanel() failure");
return false;
}
@@ -953,8 +989,7 @@ public class ConfigureDRM {
// save panel
boolean disp_save = SavePKCS12Panel();
if (!disp_save) {
- System.out
- .println("ERROR: ConfigureDRM: SavePKCS12Panel() failure");
+ System.out.println("ERROR: ConfigureDRM: SavePKCS12Panel() failure");
return false;
}
@@ -967,8 +1002,7 @@ public class ConfigureDRM {
// 13. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureDRM: AdminCertReqPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: AdminCertReqPanel() failure");
return false;
}
@@ -976,8 +1010,7 @@ public class ConfigureDRM {
// 14. Admin Cert import Panel
boolean disp_im = AdminCertImportPanel();
if (!disp_im) {
- System.out
- .println("ERROR: ConfigureDRM: AdminCertImportPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: AdminCertImportPanel() failure");
return false;
}
@@ -985,8 +1018,7 @@ public class ConfigureDRM {
// 15. Update Domain Panel
boolean disp_ud = UpdateDomainPanel();
if (!disp_ud) {
- System.out
- .println("ERROR: ConfigureDRM: UpdateDomainPanel() failure");
+ System.out.println("ERROR: ConfigureDRM: UpdateDomainPanel() failure");
return false;
}
@@ -1002,7 +1034,8 @@ public class ConfigureDRM {
}
}
- public static void main(String args[]) {
+ public static void main(String args[])
+ {
ConfigureDRM ca = new ConfigureDRM();
// set variables
@@ -1030,7 +1063,7 @@ public class ConfigureDRM {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -1094,7 +1127,7 @@ public class ConfigureDRM {
// subsystemName
StringHolder x_subsystem_name = new StringHolder();
- // clone parameters
+ //clone parameters
StringHolder x_clone = new StringHolder();
StringHolder x_clone_uri = new StringHolder();
StringHolder x_clone_p12_file = new StringHolder();
@@ -1103,187 +1136,145 @@ public class ConfigureDRM {
// parse the args
ArgParser parser = new ArgParser("ConfigureDRM");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL EE port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL EE port", x_ca_ssl_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
- parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption(
- "-secure_conn %s #use ldaps port (optional, default is false)",
- x_secure_conn);
- parser.addOption(
- "-remove_data %s #remove existing data under base_dn (optional, default is false) ",
- x_remove_data);
- parser.addOption(
- "-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)",
- x_clone_start_tls);
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption ("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption ("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption ("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption ("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption ("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption(
- "-key_type %s #Key type [RSA,ECC] (optional, default is RSA)",
- x_key_type);
- parser.addOption(
- "-key_size %s #Key Size (optional, for RSA default is 2048)",
- x_key_size);
- parser.addOption(
- "-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)",
- x_key_curvename);
- parser.addOption(
- "-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)",
- x_signing_algorithm);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_signing_algorithm);
- // key and algorithm options for transport certificate (overrides
- // default)
- parser.addOption(
- "-transport_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_transport_key_type);
- parser.addOption(
- "-transport_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_transport_key_size);
- parser.addOption(
- "-transport_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_transport_key_curvename);
- parser.addOption(
- "-transport_signingalgorithm %s #Algorithm used by the transport cert to sign objects (optional, default is signing_algorithm)",
- x_transport_signingalgorithm);
+ // key and algorithm options for transport certificate (overrides default)
+ parser.addOption("-transport_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_transport_key_type);
+ parser.addOption("-transport_key_size %s #Key Size (optional, for RSA default is key_size)", x_transport_key_size);
+ parser.addOption("-transport_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_transport_key_curvename);
+ parser.addOption("-transport_signingalgorithm %s #Algorithm used by the transport cert to sign objects (optional, default is signing_algorithm)", x_transport_signingalgorithm);
// key and algorithm options for storage certificate (overrides default)
- parser.addOption(
- "-storage_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_storage_key_type);
- parser.addOption(
- "-storage_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_storage_key_size);
- parser.addOption(
- "-storage_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_storage_key_curvename);
-
- // key and algorithm options for audit_signing certificate (overrides
- // default)
- parser.addOption(
- "-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_audit_signing_key_type);
- parser.addOption(
- "-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_audit_signing_key_size);
- parser.addOption(
- "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides
- // default)
- parser.addOption(
- "-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_subsystem_key_type);
- parser.addOption(
- "-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_subsystem_key_size);
- parser.addOption(
- "-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides
- // default)
- parser.addOption(
- "-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_sslserver_key_type);
- parser.addOption(
- "-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_sslserver_key_size);
- parser.addOption(
- "-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_sslserver_key_curvename);
+ parser.addOption("-storage_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_storage_key_type);
+ parser.addOption("-storage_key_size %s #Key Size (optional, for RSA default is key_size)", x_storage_key_size);
+ parser.addOption("-storage_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_storage_key_curvename);
+
+ // key and algorithm options for audit_signing certificate (overrides default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent Cert Subject ",
+ x_agent_cert_subject);
+
+ parser.addOption ("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
+
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)",
+ x_backup_fname);
+
+ parser.addOption (
+ "-drm_transport_cert_subject_name %s #DRM transport cert subject name",
+ x_drm_transport_cert_subject_name);
+ parser.addOption (
+ "-drm_subsystem_cert_subject_name %s #DRM subsystem cert subject name",
+ x_drm_subsystem_cert_subject_name);
+ parser.addOption (
+ "-drm_storage_cert_subject_name %s #DRM storage cert subject name",
+ x_drm_storage_cert_subject_name);
+ parser.addOption (
+ "-drm_server_cert_subject_name %s #DRM server cert subject name",
+ x_drm_server_cert_subject_name);
+
+ parser.addOption (
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
+ "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name",
+ x_drm_audit_signing_cert_subject_name);
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent Cert Subject ",
- x_agent_cert_subject);
-
- parser.addOption("-backup_pwd %s #PKCS12 password", x_backup_pwd);
-
- parser.addOption(
- "-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)",
- x_backup_fname);
-
- parser.addOption(
- "-drm_transport_cert_subject_name %s #DRM transport cert subject name",
- x_drm_transport_cert_subject_name);
- parser.addOption(
- "-drm_subsystem_cert_subject_name %s #DRM subsystem cert subject name",
- x_drm_subsystem_cert_subject_name);
- parser.addOption(
- "-drm_storage_cert_subject_name %s #DRM storage cert subject name",
- x_drm_storage_cert_subject_name);
- parser.addOption(
- "-drm_server_cert_subject_name %s #DRM server cert subject name",
- x_drm_server_cert_subject_name);
-
- parser.addOption("-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
- parser.addOption(
- "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name",
- x_drm_audit_signing_cert_subject_name);
-
- parser.addOption(
- "-clone %s #Clone of another KRA [true, false] (optional, default false)",
- x_clone);
- parser.addOption(
- "-clone_uri %s #URL of Master KRA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)",
- x_clone_uri);
- parser.addOption(
- "-clone_p12_file %s #File containing pk12 keys of Master KRA (optional, required if -clone=true)",
- x_clone_p12_file);
- parser.addOption(
- "-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)",
- x_clone_p12_passwd);
+ parser.addOption("-clone %s #Clone of another KRA [true, false] (optional, default false)", x_clone);
+ parser.addOption("-clone_uri %s #URL of Master KRA to clone. It must have the form https://<hostname>:<EE port> (optional, required if -clone=true)", x_clone_uri);
+ parser.addOption("-clone_p12_file %s #File containing pk12 keys of Master KRA (optional, required if -clone=true)", x_clone_p12_file);
+ parser.addOption("-clone_p12_password %s #Password for pk12 file (optional, required if -clone=true)", x_clone_p12_passwd);
// and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched != null) {
+ if (unmatched!=null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1328,42 +1319,31 @@ public class ConfigureDRM {
key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE);
transport_key_type = set_default(x_transport_key_type.value, key_type);
storage_key_type = set_default(x_storage_key_type.value, key_type);
- audit_signing_key_type = set_default(x_audit_signing_key_type.value,
- key_type);
+ audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type);
subsystem_key_type = set_default(x_subsystem_key_type.value, key_type);
sslserver_key_type = set_default(x_sslserver_key_type.value, key_type);
key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE);
transport_key_size = set_default(x_transport_key_size.value, key_size);
storage_key_size = set_default(x_storage_key_size.value, key_size);
- audit_signing_key_size = set_default(x_audit_signing_key_size.value,
- key_size);
+ audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size);
subsystem_key_size = set_default(x_subsystem_key_size.value, key_size);
sslserver_key_size = set_default(x_sslserver_key_size.value, key_size);
- key_curvename = set_default(x_key_curvename.value,
- DEFAULT_KEY_CURVENAME);
- transport_key_curvename = set_default(x_transport_key_curvename.value,
- key_curvename);
- storage_key_curvename = set_default(x_storage_key_curvename.value,
- key_curvename);
- audit_signing_key_curvename = set_default(
- x_audit_signing_key_curvename.value, key_curvename);
- subsystem_key_curvename = set_default(x_subsystem_key_curvename.value,
- key_curvename);
- sslserver_key_curvename = set_default(x_sslserver_key_curvename.value,
- key_curvename);
+ key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME);
+ transport_key_curvename = set_default(x_transport_key_curvename.value, key_curvename);
+ storage_key_curvename = set_default(x_storage_key_curvename.value, key_curvename);
+ audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename);
+ subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename);
+ sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename);
if (transport_key_type.equalsIgnoreCase("RSA")) {
- signing_algorithm = set_default(x_signing_algorithm.value,
- DEFAULT_KEY_ALGORITHM_RSA);
+ signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA);
} else {
- signing_algorithm = set_default(x_signing_algorithm.value,
- DEFAULT_KEY_ALGORITHM_ECC);
+ signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC);
}
- transport_signingalgorithm = set_default(
- x_transport_signingalgorithm.value, signing_algorithm);
+ transport_signingalgorithm = set_default(x_transport_signingalgorithm.value, signing_algorithm);
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
@@ -1374,13 +1354,15 @@ public class ConfigureDRM {
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-kra.p12");
-
- drm_transport_cert_subject_name = x_drm_transport_cert_subject_name.value;
- drm_subsystem_cert_subject_name = x_drm_subsystem_cert_subject_name.value;
- drm_storage_cert_subject_name = x_drm_storage_cert_subject_name.value;
- drm_server_cert_subject_name = x_drm_server_cert_subject_name.value;
- drm_audit_signing_cert_subject_name = x_drm_audit_signing_cert_subject_name.value;
-
+
+ drm_transport_cert_subject_name =
+ x_drm_transport_cert_subject_name.value ;
+ drm_subsystem_cert_subject_name =
+ x_drm_subsystem_cert_subject_name.value;
+ drm_storage_cert_subject_name = x_drm_storage_cert_subject_name.value ;
+ drm_server_cert_subject_name = x_drm_server_cert_subject_name.value ;
+ drm_audit_signing_cert_subject_name = x_drm_audit_signing_cert_subject_name.value;
+
subsystem_name = x_subsystem_name.value;
if ((x_clone.value != null) && (x_clone.value.equalsIgnoreCase("true"))) {
@@ -1393,12 +1375,12 @@ public class ConfigureDRM {
clone_p12_passwd = x_clone_p12_passwd.value;
boolean st = ca.ConfigureDRMInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create DRM");
System.exit(-1);
}
-
+
System.out.println("Certificate System - DRM Instance Configured");
System.exit(0);
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
index d82ee68b..f237b0c7 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -39,7 +38,8 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureOCSP {
+public class ConfigureOCSP
+{
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
public static final String DEFAULT_KEY_CURVENAME = "nistp256";
@@ -49,7 +49,7 @@ public class ConfigureOCSP {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ocsp/admin/console/config/login";
public static String wizard_uri = "/ocsp/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -75,7 +75,7 @@ public class ConfigureOCSP {
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -148,37 +148,42 @@ public class ConfigureOCSP {
public static String backup_pwd = null;
public static String backup_fname = null;
- // cert subject names
+ // cert subject names
public static String ocsp_sign_cert_subject_name = null;
public static String ocsp_subsystem_cert_subject_name = null;
public static String ocsp_server_cert_subject_name = null;
public static String ocsp_audit_signing_cert_subject_name = null;
public static String subsystem_name = null;
-
- public ConfigureOCSP() {
+ public ConfigureOCSP ()
+ {
// do nothing :)
}
- public void sleep_time() {
- try {
+ public void sleep_time()
+ {
+ try
+ {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- } catch (Exception e) {
+ }
+ catch(Exception e)
+ {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel() {
+ public boolean LoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -186,26 +191,28 @@ public class ConfigureOCSP {
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp != null) {
+ if (temp!=null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
+ HTTPClient.j_session_id = temp.substring(0,index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ "p=0&op=next&xml=true");
// parse xml here
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
return st;
}
- public boolean TokenChoicePanel() {
+ public boolean TokenChoicePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -215,9 +222,11 @@ public class ConfigureOCSP {
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token") + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode("Internal Key Storage Token") +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -226,19 +235,24 @@ public class ConfigureOCSP {
// HSM
else {
// login to hsm first
- query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=2" + "&op=next" + "&xml=true" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -248,18 +262,24 @@ public class ConfigureOCSP {
return true;
}
- public boolean DomainPanel() {
+ public boolean DomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
- String query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&choice=existingdomain"+
+ "&p=3" +
+ "&op=next" +
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -270,15 +290,16 @@ public class ConfigureOCSP {
}
- public boolean DisplayChainPanel() {
+ public boolean DisplayChainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -288,41 +309,46 @@ public class ConfigureOCSP {
}
- public boolean SecurityDomainLoginPanel() {
+ public boolean SecurityDomainLoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String ocsp_url = "https://" + cs_hostname + ":" + cs_port
- + "/ocsp/admin/console/config/wizard" + "?p=5&subsystem=OCSP";
- String query_string = "url=" + URLEncoder.encode(ocsp_url);
+ String ocsp_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ocsp/admin/console/config/wizard" +
+ "?p=5&subsystem=OCSP" ;
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
+ String query_string = "url=" + URLEncoder.encode(ocsp_url);
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(ocsp_url);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(ocsp_url) ;
+
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
// get session id from security domain
String ocsp_session_id = hr.getContentValue("header.session_id");
String ocsp_url_1 = hr.getContentValue("header.url");
- System.out.println("OCSP_SESSION_ID=" + ocsp_session_id);
- System.out.println("OCSP_URL=" + ocsp_url_1);
+ System.out.println("OCSP_SESSION_ID=" + ocsp_session_id );
+ System.out.println("OCSP_URL=" + ocsp_url_1 );
// use session id to connect back to OCSP
- String query_string_2 = "p=5" + "&subsystem=OCSP" + "&session_id="
- + ocsp_session_id + "&xml=true";
+ String query_string_2 = "p=5" +
+ "&subsystem=OCSP" +
+ "&session_id=" + ocsp_session_id +
+ "&xml=true" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -332,18 +358,20 @@ public class ConfigureOCSP {
return true;
}
-
- public boolean SubsystemPanel() {
+
+ public boolean SubsystemPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=5" + "&op=next" + "&xml=true"
- + "&subsystemName=" + URLEncoder.encode(subsystem_name)
- + "&choice=newsubsystem";
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&choice=newsubsystem" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -352,25 +380,27 @@ public class ConfigureOCSP {
return true;
}
- public boolean LdapConnectionPanel() {
+ public boolean LdapConnectionPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=7" + "&op=next" + "&xml=true" + "&host="
- + URLEncoder.encode(ldap_host) + "&port="
- + URLEncoder.encode(ldap_port) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true") ? "&secureConn=on" : "")
- + (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "")
- + (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=7" + "&op=next" + "&xml=true" +
+ "&host=" + URLEncoder.encode(ldap_host) +
+ "&port=" + URLEncoder.encode(ldap_port) +
+ "&binddn=" + URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" + URLEncoder.encode(bind_password) +
+ "&basedn=" + URLEncoder.encode(base_dn) +
+ "&database=" + URLEncoder.encode(db_name) +
+ "&display=" + URLEncoder.encode("$displayStr") +
+ (secure_conn.equals("true")? "&secureConn=on": "") +
+ (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
+ (remove_data.equals("true")? "&removeData=true": "");
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -380,65 +410,50 @@ public class ConfigureOCSP {
return true;
}
- public boolean KeyPanel() {
+ public boolean KeyPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
ArrayList<String> al = null;
- String query_string = "p=8" + "&op=next" + "&xml=true"
- + "&signing_custom_size="
- + signing_key_size
- + "&subsystem_custom_size="
- + subsystem_key_size
- + "&sslserver_custom_size="
- + sslserver_key_size
- + "&audit_signing_custom_size="
- + audit_signing_key_size
- + "&custom_size="
- + key_size
- + "&signing_custom_curvename="
- + signing_key_curvename
- + "&subsystem_custom_curvename="
- + subsystem_key_curvename
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename
- + "&audit_signing_custom_curvename="
- + audit_signing_key_curvename
- + "&custom_curvename="
- + key_curvename
- + "&signing_keytype="
- + signing_key_type
- + "&subsystem_keytype="
- + subsystem_key_type
- + "&sslserver_keytype="
- + sslserver_key_type
- + "&audit_signing_keytype="
- + audit_signing_key_type
- + "&keytype="
- + key_type
- + "&signing_choice=custom"
- + "&subsystem_choice=custom"
- + "&sslserver_choice=custom"
- + "&audit_signing_choice=custom"
- + "&signingalgorithm="
- + signing_algorithm
- + "&signing_signingalgorithm="
- + signing_signingalgorithm + "&choice=custom";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=8" + "&op=next" + "&xml=true" +
+ "&signing_custom_size=" + signing_key_size +
+ "&subsystem_custom_size=" + subsystem_key_size +
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&audit_signing_custom_size=" + audit_signing_key_size +
+ "&custom_size=" + key_size +
+ "&signing_custom_curvename=" + signing_key_curvename +
+ "&subsystem_custom_curvename=" + subsystem_key_curvename +
+ "&sslserver_custom_curvename=" + sslserver_key_curvename +
+ "&audit_signing_custom_curvename=" + audit_signing_key_curvename +
+ "&custom_curvename=" + key_curvename +
+ "&signing_keytype=" + signing_key_type +
+ "&subsystem_keytype=" + subsystem_key_type +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&audit_signing_keytype=" + audit_signing_key_type +
+ "&keytype=" + key_type +
+ "&signing_choice=custom"+
+ "&subsystem_choice=custom"+
+ "&sslserver_choice=custom"+
+ "&audit_signing_choice=custom" +
+ "&signingalgorithm=" + signing_algorithm +
+ "&signing_signingalgorithm=" + signing_signingalgorithm +
+ "&choice=custom";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair", "DN");
+
+ al = px.constructValueList("CertReqPair","DN");
// get ca cert subject name
if (al != null) {
- for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
+ for (int i=0; i < al.size(); i++) {
+ String temp = al.get(i);
if (temp.indexOf("OCSP Signing") > 0) {
ocsp_signing_cert_name = temp;
} else if (temp.indexOf("OCSP Subsystem") > 0) {
@@ -450,19 +465,17 @@ public class ConfigureOCSP {
}
}
}
-
- System.out.println("default: ocsp_signing_cert_name="
- + ocsp_signing_cert_name);
- System.out.println("default: ocsp_subsystem_cert_name="
- + ocsp_subsystem_cert_name);
+
+ System.out.println("default: ocsp_signing_cert_name=" + ocsp_signing_cert_name);
+ System.out.println("default: ocsp_subsystem_cert_name=" + ocsp_subsystem_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
- System.out.println("default: oscp_audit_signing_cert_name="
- + ocsp_audit_signing_cert_name);
+ System.out.println("default: oscp_audit_signing_cert_name=" + ocsp_audit_signing_cert_name);
return true;
}
- public boolean CertSubjectPanel() {
+ public boolean CertSubjectPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -471,52 +484,57 @@ public class ConfigureOCSP {
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
- String query_string = "p=9" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(ocsp_subsystem_cert_subject_name)
- + "&signing=" + URLEncoder.encode(ocsp_sign_cert_subject_name)
- + "&sslserver="
- + URLEncoder.encode(ocsp_server_cert_subject_name)
- + "&audit_signing="
- + URLEncoder.encode(ocsp_audit_signing_cert_subject_name)
- + "&urls=" + URLEncoder.encode(domain_url) + "";
+ String query_string = "p=9" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(ocsp_subsystem_cert_subject_name) +
+ "&signing=" +
+ URLEncoder.encode(ocsp_sign_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(ocsp_server_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(ocsp_audit_signing_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url) +
+ "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair", "Request");
- cert_list = px.constructValueList("CertReqPair", "Certificate");
- dn_list = px.constructValueList("CertReqPair", "Nickname");
+
+ req_list = px.constructValueList("CertReqPair","Request");
+ cert_list = px.constructValueList("CertReqPair","Certificate");
+ dn_list = px.constructValueList("CertReqPair","Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_signing_cert_req = req_list.get(i);
- ocsp_signing_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("subsystemCert") >= 0) {
- ocsp_subsystem_cert_req = req_list.get(i);
- ocsp_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >= 0) {
- ocsp_audit_signing_cert_req = req_list.get(i);
- ocsp_audit_signing_cert_cert = cert_list.get(i);
+ for (int i=0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("ocspSigningCert") >= 0 ) {
+ ocsp_signing_cert_req = req_list.get(i);
+ ocsp_signing_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("subsystemCert") >= 0 ) {
+ ocsp_subsystem_cert_req = req_list.get(i);
+ ocsp_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >=0) {
+ ocsp_audit_signing_cert_req = req_list.get(i);
+ ocsp_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel() {
+ public boolean CertificatePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -526,58 +544,69 @@ public class ConfigureOCSP {
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
- String query_string = "p=10" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(ocsp_subsystem_cert_cert)
- + "&subsystem_cc=" + "&signing="
- + URLEncoder.encode(ocsp_signing_cert_cert) + "&signing_cc="
- + "&sslserver=" + URLEncoder.encode(server_cert_cert)
- + "&sslserver_cc=" + "&audit_signing="
- + URLEncoder.encode(ocsp_audit_signing_cert_cert)
- + "&audit_signing_cc=" + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=10" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(ocsp_subsystem_cert_cert) +
+ "&subsystem_cc=" +
+ "&signing=" +
+ URLEncoder.encode(ocsp_signing_cert_cert) +
+ "&signing_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&audit_signing=" +
+ URLEncoder.encode(ocsp_audit_signing_cert_cert) +
+ "&audit_signing_cc=" +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
-
+
System.out.println("html returned=" + hr.getHTML());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel() {
+ public boolean BackupPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=11" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd="
- + URLEncoder.encode(backup_pwd) + "&__pwdagain="
- + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=11" + "&op=next" + "&xml=true" +
+ "&choice=backupkey" +
+ "&__pwd=" + URLEncoder.encode(backup_pwd) +
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel() {
+ public boolean SavePKCS12Panel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "";
- hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
+ String query_string = "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
// dump hr.getResponseData() to file
@@ -587,18 +616,17 @@ public class ConfigureOCSP {
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod", "600", backup_fname };
+ String rtParams[] = { "chmod","600", backup_fname};
Process proc = Runtime.getRuntime().exec(rtParams);
- BufferedReader br = new BufferedReader(new InputStreamReader(
- proc.getErrorStream()));
+ BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ((line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ( (line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -606,14 +634,14 @@ public class ConfigureOCSP {
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: " + pfx.getVersion());
+ System.out.println("Version: "+pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has " + asSeq.size()
- + " SafeContents");
+ System.out.println("AuthSafes has "+
+ asSeq.size()+" SafeContents");
fis.close();
- } catch (Exception e) {
+ } catch(Exception e) {
System.out.println("ERROR: Exception=" + e.getMessage());
return false;
}
@@ -621,17 +649,22 @@ public class ConfigureOCSP {
return true;
}
- public boolean AdminCertReqPanel() {
+ public boolean AdminCertReqPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
+
String cert_subject = "CN=ocsp-" + admin_user;
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.setTransportCert(null);
@@ -641,67 +674,78 @@ public class ConfigureOCSP {
String crmf_request = cCrypt.generateCRMFrequest();
if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
return false;
}
admin_cert_request = crmf_request;
- String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
- + "&name=" + admin_user + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&profileId="
- + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
- + "&cert_request=" + URLEncoder.encode(admin_cert_request)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&clone=new" + "&import=true" + "&securitydomain="
- + URLEncoder.encode(domain_name) + "";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=13" + "&op=next" + "&xml=true" +
+ "&cert_request_type=" + "crmf" +
+ "&uid=" + admin_user +
+ "&name=" + admin_user +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&profileId=" + "caAdminCert" +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&clone=new" +
+ "&import=true" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel() {
+ public boolean AdminCertImportPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true" + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "";
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
+
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import = OSUtil.BtoA(hr.getResponseData());
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -709,30 +753,37 @@ public class ConfigureOCSP {
return true;
}
- public boolean UpdateDomainPanel() {
+ public boolean UpdateDomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=14" + "&op=next" + "&xml=true" + "&caHost="
- + URLEncoder.encode(sd_hostname) + "&caPort="
- + URLEncoder.encode(sd_agent_port) + "";
+ String query_string = "p=14" + "&op=next" + "&xml=true" +
+ "&caHost=" + URLEncoder.encode(sd_hostname) +
+ "&caPort=" + URLEncoder.encode(sd_agent_port) +
+ "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean ConfigureOCSPInstance() {
+
+ public boolean ConfigureOCSPInstance()
+ {
// 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
@@ -751,8 +802,7 @@ public class ConfigureOCSP {
// 2. Token Choice Panel
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out
- .println("ERROR: ConfigureOCSP: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: TokenChoicePanel() failure");
return false;
}
@@ -768,8 +818,7 @@ public class ConfigureOCSP {
// 4. display cert chain panel
boolean disp_st = DisplayChainPanel();
if (!disp_st) {
- System.out
- .println("ERROR: ConfigureOCSP: DisplayChainPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: DisplayChainPanel() failure");
return false;
}
@@ -777,8 +826,7 @@ public class ConfigureOCSP {
// security domain login panel
boolean disp_sd = SecurityDomainLoginPanel();
if (!disp_sd) {
- System.out
- .println("ERROR: ConfigureOCSP: SecurityDomainLoginPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: SecurityDomainLoginPanel() failure");
return false;
}
@@ -786,17 +834,15 @@ public class ConfigureOCSP {
// subsystem panel
boolean disp_ss = SubsystemPanel();
if (!disp_ss) {
- System.out
- .println("ERROR: ConfigureOCSP: SubsystemPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureOCSP: LdapConnectionPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: LdapConnectionPanel() failure");
return false;
}
@@ -813,8 +859,7 @@ public class ConfigureOCSP {
// 10. Cert Subject Panel
boolean disp_csubj = CertSubjectPanel();
if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureOCSP: CertSubjectPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: CertSubjectPanel() failure");
return false;
}
@@ -822,8 +867,7 @@ public class ConfigureOCSP {
// 11. Certificate Panel
boolean disp_cp = CertificatePanel();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureOCSP: CertificatePanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: CertificatePanel() failure");
return false;
}
@@ -839,8 +883,7 @@ public class ConfigureOCSP {
// save panel
boolean disp_save = SavePKCS12Panel();
if (!disp_save) {
- System.out
- .println("ERROR: ConfigureOCSP: SavePKCS12Panel() failure");
+ System.out.println("ERROR: ConfigureOCSP: SavePKCS12Panel() failure");
return false;
}
@@ -848,8 +891,7 @@ public class ConfigureOCSP {
// 13. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureOCSP: AdminCertReqPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: AdminCertReqPanel() failure");
return false;
}
@@ -857,8 +899,7 @@ public class ConfigureOCSP {
// 14. Admin Cert import Panel
boolean disp_im = AdminCertImportPanel();
if (!disp_im) {
- System.out
- .println("ERROR: ConfigureOCSP: AdminCertImportPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: AdminCertImportPanel() failure");
return false;
}
@@ -866,8 +907,7 @@ public class ConfigureOCSP {
// 15. Update Domain Panel
boolean disp_ud = UpdateDomainPanel();
if (!disp_ud) {
- System.out
- .println("ERROR: ConfigureOCSP: UpdateDomainPanel() failure");
+ System.out.println("ERROR: ConfigureOCSP: UpdateDomainPanel() failure");
return false;
}
@@ -883,7 +923,8 @@ public class ConfigureOCSP {
}
}
- public static void main(String args[]) {
+ public static void main(String args[])
+ {
ConfigureOCSP ca = new ConfigureOCSP();
// set variables
@@ -911,7 +952,7 @@ public class ConfigureOCSP {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -972,160 +1013,132 @@ public class ConfigureOCSP {
// parse the args
ArgParser parser = new ArgParser("ConfigureOCSP");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain Admin Name",
- x_sd_admin_name);
- parser.addOption(
- "-sd_admin_password %s #Security Domain Admin password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL EE port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL EE port", x_ca_ssl_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
- parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption(
- "-secure_conn %s #use ldaps port (optional, default is false)",
- x_secure_conn);
- parser.addOption(
- "-remove_data %s #remove existing data under base_dn (optional, default is false) ",
- x_remove_data);
- parser.addOption(
- "-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)",
- x_clone_start_tls);
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain Admin Name",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain Admin password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption ("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption ("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption ("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption ("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption ("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption(
- "-key_type %s #Key type [RSA,ECC] (optional, default is RSA)",
- x_key_type);
- parser.addOption(
- "-key_size %s #Key Size (optional, for RSA default is 2048)",
- x_key_size);
- parser.addOption(
- "-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)",
- x_key_curvename);
- parser.addOption(
- "-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)",
- x_signing_algorithm);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_signing_algorithm);
// key and algorithm options for signing certificate (overrides default)
- parser.addOption(
- "-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_signing_key_type);
- parser.addOption(
- "-signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_signing_key_size);
- parser.addOption(
- "-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_signing_key_curvename);
- parser.addOption(
- "-signing_signingalgorithm %s #Algorithm used be ocsp signing cert to sign objects (optional, default is signing_algorithm)",
- x_signing_signingalgorithm);
-
- // key and algorithm options for audit_signing certificate (overrides
- // default)
- parser.addOption(
- "-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_audit_signing_key_type);
- parser.addOption(
- "-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_audit_signing_key_size);
- parser.addOption(
- "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_audit_signing_key_curvename);
+ parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
+ parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
+ parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
+ parser.addOption("-signing_signingalgorithm %s #Algorithm used be ocsp signing cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
+
+ // key and algorithm options for audit_signing certificate (overrides default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption ("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
+
+ parser.addOption (
+ "-ocsp_sign_cert_subject_name %s #OCSP cert subject name",
+ x_ocsp_sign_cert_subject_name);
+ parser.addOption (
+ "-ocsp_subsystem_cert_subject_name %s #OCSP subsystem cert subject name",
+ x_ocsp_subsystem_cert_subject_name);
+ parser.addOption (
+ "-ocsp_server_cert_subject_name %s #OCSP server cert subject name",
+ x_ocsp_server_cert_subject_name);
+
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-ocsp.p12",
+ x_backup_fname);
+
+ parser.addOption (
+ "-subsystem_name %s #OCSP subsystem name",
+ x_subsystem_name);
- // key and algorithm options for subsystem certificate (overrides
- // default)
- parser.addOption(
- "-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_subsystem_key_type);
- parser.addOption(
- "-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_subsystem_key_size);
- parser.addOption(
- "-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides
- // default)
- parser.addOption(
- "-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_sslserver_key_type);
- parser.addOption(
- "-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_sslserver_key_size);
parser.addOption(
- "-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_sslserver_key_curvename);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
-
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
-
- parser.addOption("-backup_pwd %s #PKCS12 password", x_backup_pwd);
-
- parser.addOption(
- "-ocsp_sign_cert_subject_name %s #OCSP cert subject name",
- x_ocsp_sign_cert_subject_name);
- parser.addOption(
- "-ocsp_subsystem_cert_subject_name %s #OCSP subsystem cert subject name",
- x_ocsp_subsystem_cert_subject_name);
- parser.addOption(
- "-ocsp_server_cert_subject_name %s #OCSP server cert subject name",
- x_ocsp_server_cert_subject_name);
-
- parser.addOption(
- "-backup_fname %s #Backup File for p12, (optional, default /root/tmp-ocsp.p12",
- x_backup_fname);
-
- parser.addOption("-subsystem_name %s #OCSP subsystem name",
- x_subsystem_name);
-
- parser.addOption(
- "-ocsp_audit_signing_cert_subject_name %s #OCSP audit signing cert subject name",
- x_ocsp_audit_signing_cert_subject_name);
+ "-ocsp_audit_signing_cert_subject_name %s #OCSP audit signing cert subject name",
+ x_ocsp_audit_signing_cert_subject_name);
// and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched != null) {
+ if (unmatched!=null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1169,38 +1182,28 @@ public class ConfigureOCSP {
key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE);
signing_key_type = set_default(x_signing_key_type.value, key_type);
- audit_signing_key_type = set_default(x_audit_signing_key_type.value,
- key_type);
+ audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type);
subsystem_key_type = set_default(x_subsystem_key_type.value, key_type);
sslserver_key_type = set_default(x_sslserver_key_type.value, key_type);
key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE);
signing_key_size = set_default(x_signing_key_size.value, key_size);
- audit_signing_key_size = set_default(x_audit_signing_key_size.value,
- key_size);
+ audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size);
subsystem_key_size = set_default(x_subsystem_key_size.value, key_size);
sslserver_key_size = set_default(x_sslserver_key_size.value, key_size);
- key_curvename = set_default(x_key_curvename.value,
- DEFAULT_KEY_CURVENAME);
- signing_key_curvename = set_default(x_signing_key_curvename.value,
- key_curvename);
- audit_signing_key_curvename = set_default(
- x_audit_signing_key_curvename.value, key_curvename);
- subsystem_key_curvename = set_default(x_subsystem_key_curvename.value,
- key_curvename);
- sslserver_key_curvename = set_default(x_sslserver_key_curvename.value,
- key_curvename);
+ key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME);
+ signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename);
+ audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename);
+ subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename);
+ sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename);
if (signing_key_type.equalsIgnoreCase("RSA")) {
- signing_algorithm = set_default(x_signing_algorithm.value,
- DEFAULT_KEY_ALGORITHM_RSA);
+ signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA);
} else {
- signing_algorithm = set_default(x_signing_algorithm.value,
- DEFAULT_KEY_ALGORITHM_ECC);
+ signing_algorithm = set_default(x_signing_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC);
}
- signing_signingalgorithm = set_default(
- x_signing_signingalgorithm.value, signing_algorithm);
+ signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm);
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
@@ -1211,24 +1214,26 @@ public class ConfigureOCSP {
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-ocsp.p12");
+
+ ocsp_sign_cert_subject_name = x_ocsp_sign_cert_subject_name.value ;
+ ocsp_subsystem_cert_subject_name =
+ x_ocsp_subsystem_cert_subject_name.value;
+ ocsp_server_cert_subject_name = x_ocsp_server_cert_subject_name.value ;
+ ocsp_audit_signing_cert_subject_name = x_ocsp_audit_signing_cert_subject_name.value;
+
+ subsystem_name = x_subsystem_name.value ;
- ocsp_sign_cert_subject_name = x_ocsp_sign_cert_subject_name.value;
- ocsp_subsystem_cert_subject_name = x_ocsp_subsystem_cert_subject_name.value;
- ocsp_server_cert_subject_name = x_ocsp_server_cert_subject_name.value;
- ocsp_audit_signing_cert_subject_name = x_ocsp_audit_signing_cert_subject_name.value;
-
- subsystem_name = x_subsystem_name.value;
boolean st = ca.ConfigureOCSPInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create OCSP");
System.exit(-1);
}
-
+
System.out.println("Certificate System - OCSP Instance Configured");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
index 4ac4837b..fc28e8b4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -30,801 +29,927 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureRA {
-
- // define global variables
-
- public static HTTPClient hc = null;
-
- public static String login_uri = "/ra/admin/console/config/login";
- public static String wizard_uri = "/ra/admin/console/config/wizard";
- public static String admin_uri = "/ca/admin/ca/getBySerial";
-
- public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
- public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
- public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
- public static String pkcs12_uri = "/ra/admin/console/config/savepkcs12";
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String cs_clientauth_port = null;
-
- public static String sd_hostname = null;
- public static String sd_ssl_port = null;
- public static String sd_agent_port = null;
- public static String sd_admin_port = null;
- public static String sd_admin_name = null;
- public static String sd_admin_password = null;
-
- public static String ca_hostname = null;
- public static String ca_port = null;
- public static String ca_ssl_port = null;
- public static String ca_admin_port = null;
-
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
-
- // Login Panel
- public static String pin = null;
-
- public static String domain_name = null;
-
- public static String admin_user = null;
- public static String admin_email = null;
- public static String admin_password = null;
- public static String admin_serial_number = null;
- public static String agent_name = null;
-
- public static String key_size = null;
- public static String key_type = null;
- public static String token_name = null;
- public static String token_pwd = null;
-
- public static String agent_key_size = null;
- public static String agent_key_type = null;
- public static String agent_cert_subject = null;
-
- public static String server_cert_name = null;
- public static String server_cert_req = null;
- public static String server_cert_pp = null;
- public static String server_cert_cert = null;
-
- public static String ra_subsystem_cert_name = null;
- public static String ra_subsystem_cert_req = null;
- public static String ra_subsystem_cert_pp = null;
- public static String ra_subsystem_cert_cert = null;
-
- // names
- public static String ra_server_cert_subject_name = null;
- public static String ra_server_cert_nickname = null;
- public static String ra_subsystem_cert_subject_name = null;
- public static String ra_subsystem_cert_nickname = null;
- public static String subsystem_name = null;
-
- // Security Domain Login Panel
- public static String ra_session_id = null;
-
- // Admin Certificate Request Panel
- public static String requestor_name = null;
-
- public ConfigureRA() {
- // do nothing :)
- }
-
- public void sleep_time() {
- try {
- System.out.println("Sleeping for 5 secs..");
- Thread.sleep(5000);
- } catch (Exception e) {
- System.out.println("ERROR: sleep problem");
- }
-
- }
-
- public boolean LoginPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
- System.out.println("xml returned: " + hr.getHTML());
-
- // parse xml here - nothing to parse
-
- // no cookie for ra
- // get cookie
- String temp = hr.getCookieValue("pin");
-
- if (temp != null) {
- int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
- st = true;
- }
-
- hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
-
- // parse xml here
-
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- st = true;
- return st;
- }
-
- public boolean DomainPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
-
- String query_string = "p=1" + "&choice=existingdomain" + "&sdomainURL="
- + URLEncoder.encode(domain_url) + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
-
- }
-
- public boolean DisplayChainPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String query_string = null;
-
- query_string = "p=2" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- return true;
-
- }
-
- public boolean SecurityDomainLoginPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String ra_url = "https://" + cs_hostname + ":" + cs_port
- + "/ra/admin/console/config/wizard" + "?p=3&subsystem=RA";
-
- String query_string = "url=" + URLEncoder.encode(ra_url) + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
-
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(ra_url) + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
-
- // get session id from security domain
- sleep_time();
-
- ra_session_id = hr.getContentValue("header.session_id");
- String ra_url_1 = hr.getContentValue("header.url");
+public class ConfigureRA
+{
+
+
+ // define global variables
+
+ public static HTTPClient hc = null;
+
+ public static String login_uri = "/ra/admin/console/config/login";
+ public static String wizard_uri = "/ra/admin/console/config/wizard";
+ public static String admin_uri = "/ca/admin/ca/getBySerial";
+
+ public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
+ public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
+ public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
+ public static String pkcs12_uri = "/ra/admin/console/config/savepkcs12";
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String cs_clientauth_port = null;
+
+ public static String sd_hostname = null;
+ public static String sd_ssl_port = null;
+ public static String sd_agent_port = null;
+ public static String sd_admin_port = null;
+ public static String sd_admin_name = null;
+ public static String sd_admin_password = null;
+
+ public static String ca_hostname = null;
+ public static String ca_port = null;
+ public static String ca_ssl_port = null;
+ public static String ca_admin_port = null;
+
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+
+ // Login Panel
+ public static String pin = null;
+
+ public static String domain_name = null;
+
+ public static String admin_user = null;
+ public static String admin_email = null;
+ public static String admin_password = null;
+ public static String admin_serial_number = null;
+ public static String agent_name = null;
+
+ public static String key_size = null;
+ public static String key_type = null;
+ public static String token_name = null;
+ public static String token_pwd = null;
+
+ public static String agent_key_size = null;
+ public static String agent_key_type = null;
+ public static String agent_cert_subject = null;
+
+ public static String server_cert_name = null;
+ public static String server_cert_req = null;
+ public static String server_cert_pp = null;
+ public static String server_cert_cert = null;
+
+ public static String ra_subsystem_cert_name = null;
+ public static String ra_subsystem_cert_req = null;
+ public static String ra_subsystem_cert_pp = null;
+ public static String ra_subsystem_cert_cert = null;
+
+ // names
+ public static String ra_server_cert_subject_name = null;
+ public static String ra_server_cert_nickname = null;
+ public static String ra_subsystem_cert_subject_name = null;
+ public static String ra_subsystem_cert_nickname = null;
+ public static String subsystem_name = null;
+
+ // Security Domain Login Panel
+ public static String ra_session_id = null;
+
+ // Admin Certificate Request Panel
+ public static String requestor_name = null;
+
+ public ConfigureRA ()
+ {
+ // do nothing :)
+ }
+
+ public void sleep_time()
+ {
+ try
+ {
+ System.out.println("Sleeping for 5 secs..");
+ Thread.sleep(5000);
+ }
+ catch(Exception e)
+ {
+ System.out.println("ERROR: sleep problem");
+ }
+
+ }
- System.out.println("RA_SESSION_ID=" + ra_session_id);
- System.out.println("RA_URL=" + ra_url_1);
+ public boolean LoginPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ System.out.println("xml returned: " + hr.getHTML());
+
+ // parse xml here - nothing to parse
+
+ // no cookie for ra
+ // get cookie
+ String temp = hr.getCookieValue("pin");
- // use session id to connect back to RA
+ if(temp!=null)
+ {
+ int index = temp.indexOf(";");
+ HTTPClient.j_session_id = temp.substring(0,index);
+ st = true;
+ }
+
+ hr = null;
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ "p=0&op=next&xml=true");
- String query_string_2 = "p=3" + "&subsystem=RA" + "&session_id="
- + ra_session_id + "&xml=true";
+ // parse xml here
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
- // parse xml - no parsing
+ st = true;
+ return st;
+ }
- return true;
+ public boolean DomainPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "p=1" +
+ "&choice=existingdomain" +
+ "&sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+
+ }
+
+ public boolean DisplayChainPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String query_string = null;
+
+ query_string = "p=2" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ return true;
- }
+ }
- public boolean SubsystemPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
+ public boolean SecurityDomainLoginPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
- sleep_time();
- String query_string = "p=3" + "&choice=newsubsystem"
- + "&subsystemName=" + URLEncoder.encode(subsystem_name)
- + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+ String ra_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ra/admin/console/config/wizard" +
+ "?p=3&subsystem=RA" ;
- sleep_time();
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+ String query_string = "url=" + URLEncoder.encode(ra_url) + "";
- // CA choice panel
- query_string = "p=4" + "&urls=0" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(ra_url) +
+ "" ;
- return true;
- }
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
- public boolean DBPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
+ // get session id from security domain
+ sleep_time();
- // SQL LITE PANEL
+ ra_session_id = hr.getContentValue("header.session_id");
+ String ra_url_1 = hr.getContentValue("header.url");
- String query_string = "p=5" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+ System.out.println("RA_SESSION_ID=" + ra_session_id );
+ System.out.println("RA_URL=" + ra_url_1 );
- return true;
- }
+ // use session id to connect back to RA
- public boolean TokenChoicePanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- // //////////////////////////////////////////////////////
- String query_string = null;
-
- // Software Token
- if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=6" + "&choice="
- + URLEncoder.encode("NSS Certificate DB") + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
- }
- // HSM
- else {
- // login to hsm first
- query_string = "p=7" + "&uTokName=" + URLEncoder.encode(token_name)
- + "&__uPasswd=" + URLEncoder.encode(token_pwd) + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // choice with token name now
- query_string = "p=6" + "&choice=" + URLEncoder.encode(token_name)
- + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- }
-
- return true;
- }
-
- public boolean KeyPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "p=8" + "&keytype=" + key_type
- + "&choice=default" + "&custom_size=" + key_size
- + "&sslserver_keytype=" + key_type + "&sslserver_choice=custom"
- + "&sslserver_custom_size=" + key_size + "&subsystem_keytype="
- + key_type + "&subsystem_choice=custom"
- + "&subsystem_custom_size=" + key_size + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertSubjectPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
-
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
-
- String query_string = "p=9" + "&sslserver="
- + URLEncoder.encode(ra_server_cert_subject_name)
- + "&sslserver_nick="
- + URLEncoder.encode(ra_server_cert_nickname) + "&subsystem="
- + URLEncoder.encode(ra_subsystem_cert_subject_name)
- + "&subsystem_nick="
- + URLEncoder.encode(ra_subsystem_cert_nickname) + "&urls=0"
- + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertificatePanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "p=10" + "&sslserver=" + "&sslserver_cc="
- + "&subsystem=" + "&subsystem_cc=" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean AdminCertReqPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String admin_cert_request = null;
-
- requestor_name = "RA-" + cs_hostname + "-" + cs_clientauth_port;
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.setTransportCert(null);
- cCrypt.setDualKey(false);
- cCrypt.loginDB();
-
- String crmf_request = cCrypt.generateCRMFrequest();
-
- if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
- }
-
- admin_cert_request = crmf_request;
-
- String query_string = "p=11" + "&uid=" + admin_user + "&name="
- + URLEncoder.encode("RA Administrator") + "&email="
- + URLEncoder.encode(admin_email) + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&cert_request="
- + URLEncoder.encode(admin_cert_request) + "&display=0"
- + "&profileId=" + "caAdminCert" + "&cert_request_type="
- + "crmf" + "&import=true" + "&uid=" + admin_user + "&clone=0"
- + "&securitydomain=" + URLEncoder.encode(domain_name)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&requestor_name=" + URLEncoder.encode(requestor_name)
- + "&sessionID=" + ra_session_id + "&auth_hostname="
- + ca_hostname + "&auth_port=" + ca_ssl_port + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
-
- return true;
- }
-
- public boolean AdminCertImportPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String cert_to_import = null;
-
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true" + "";
-
- // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
- // whereas RA and TPS use the CA Admin Port associated with
- // the 'CA choice panel' as invoked from the SubsystemPanel()
- // which MAY or MAY NOT be the same CA as the CA specified
- // by the Security Domain.
- hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string);
-
- try {
- // cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- cert_to_import = OSUtil.BtoA(hr.getResponseData());
-
- } catch (Exception e) {
- System.out.println("ERROR: failed to retrieve cert");
- }
-
- System.out.println("Imported Cert=" + cert_to_import);
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
-
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
- if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
- return false;
- }
-
- System.out.println("SUCCESS: imported admin user cert");
-
- String query_string_1 = "p=12" + "&serialNumber=" + admin_serial_number
- + "&caHost=" + URLEncoder.encode(ca_hostname) + "&caPort="
- + ca_admin_port + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean ConfigureRAInstance() {
- // 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- // instantiate http client
- hc = new HTTPClient();
-
- sleep_time();
- // 1. Login panel
- boolean log_st = LoginPanel();
- if (!log_st) {
- System.out.println("ERROR: JSESSIONID not found.");
- System.out.println("ERROR: ConfigureRA: LoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 2. domain panel
- boolean dom_st = DomainPanel();
- if (!dom_st) {
- System.out.println("ERROR: ConfigureRA: DomainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 3. display cert chain panel
- boolean disp_st = DisplayChainPanel();
- if (!disp_st) {
- System.out
- .println("ERROR: ConfigureRA: DisplayChainPanel() failure");
- return false;
- }
-
- sleep_time();
- // security domain login panel
- boolean disp_sd = SecurityDomainLoginPanel();
- if (!disp_sd) {
- System.out
- .println("ERROR: ConfigureRA: SecurityDomainLoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 4. subsystem panel
- boolean disp_ss = SubsystemPanel();
- if (!disp_ss) {
- System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure");
- return false;
- }
-
- sleep_time();
- // 5. ldap connection panel
- boolean disp_ldap = DBPanel();
- if (!disp_ldap) {
- System.out.println("ERROR: ConfigureRA: DBPanel() failure");
- return false;
- }
-
- sleep_time();
- // 6. Token Choice Panel
- boolean disp_token = TokenChoicePanel();
- if (!disp_token) {
- System.out
- .println("ERROR: ConfigureRA: TokenChoicePanel() failure");
- return false;
- }
-
- sleep_time();
- // 8. Key Panel
- boolean disp_key = KeyPanel();
- if (!disp_key) {
- System.out.println("ERROR: ConfigureRA: KeyPanel() failure");
- return false;
- }
-
- sleep_time();
- // 9. Cert Subject Panel
- boolean disp_csubj = CertSubjectPanel();
- if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureRA: CertSubjectPanel() failure");
- return false;
- }
-
- sleep_time();
- // 10. Certificate Panel
- boolean disp_cp = CertificatePanel();
- if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureRA: CertificatePanel() failure");
- return false;
- }
-
- sleep_time();
- // 11. Admin Cert Req Panel
- boolean disp_adm = AdminCertReqPanel();
- if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureRA: AdminCertReqPanel() failure");
- return false;
- }
-
- sleep_time();
- // 12. Admin Cert import Panel
- boolean disp_im = AdminCertImportPanel();
- if (!disp_im) {
- System.out
- .println("ERROR: ConfigureRA: AdminCertImportPanel() failure");
- return false;
- }
-
- return true;
- }
-
- public static void main(String args[]) {
- ConfigureRA ca = new ConfigureRA();
-
- // set variables
- StringHolder x_cs_hostname = new StringHolder();
- StringHolder x_cs_port = new StringHolder();
- StringHolder x_cs_clientauth_port = new StringHolder();
-
- StringHolder x_sd_hostname = new StringHolder();
- StringHolder x_sd_ssl_port = new StringHolder();
- StringHolder x_sd_agent_port = new StringHolder();
- StringHolder x_sd_admin_port = new StringHolder();
- StringHolder x_sd_admin_name = new StringHolder();
- StringHolder x_sd_admin_password = new StringHolder();
-
- StringHolder x_ca_hostname = new StringHolder();
- StringHolder x_ca_port = new StringHolder();
- StringHolder x_ca_ssl_port = new StringHolder();
- StringHolder x_ca_admin_port = new StringHolder();
-
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_preop_pin = new StringHolder();
-
- StringHolder x_domain_name = new StringHolder();
-
- StringHolder x_admin_user = new StringHolder();
- StringHolder x_admin_email = new StringHolder();
- StringHolder x_admin_password = new StringHolder();
-
- // key size
- StringHolder x_token_name = new StringHolder();
- StringHolder x_token_pwd = new StringHolder();
- StringHolder x_key_size = new StringHolder();
- StringHolder x_key_type = new StringHolder();
-
- StringHolder x_agent_key_size = new StringHolder();
- StringHolder x_agent_key_type = new StringHolder();
- StringHolder x_agent_cert_subject = new StringHolder();
-
- StringHolder x_agent_name = new StringHolder();
-
- // ra cert subject name params
- StringHolder x_ra_server_cert_subject_name = new StringHolder();
- StringHolder x_ra_server_cert_nickname = new StringHolder();
- StringHolder x_ra_subsystem_cert_subject_name = new StringHolder();
- StringHolder x_ra_subsystem_cert_nickname = new StringHolder();
-
- // subsystemName
- StringHolder x_subsystem_name = new StringHolder();
-
- // parse the args
- ArgParser parser = new ArgParser("ConfigureRA");
-
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL port", x_cs_port);
- parser.addOption("-cs_clientauth_port %s #CS SSL port",
- x_cs_clientauth_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL port", x_ca_ssl_port);
- parser.addOption("-ca_admin_port %s #CA SSL Admin port",
- x_ca_admin_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption("-token_pwd %s #HSM/Software Token password",
- x_token_pwd);
- parser.addOption("-key_size %s #Key Size", x_key_size);
- parser.addOption("-key_type %s #Key type [rsa,ecc]", x_key_type);
-
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent cert Subject",
- x_agent_cert_subject);
-
- parser.addOption(
- "-ra_server_cert_subject_name %s #RA server cert subject name",
- x_ra_server_cert_subject_name);
- parser.addOption(
- "-ra_server_cert_nickname %s #RA server cert nickname",
- x_ra_server_cert_nickname);
- parser.addOption(
- "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name",
- x_ra_subsystem_cert_subject_name);
- parser.addOption(
- "-ra_subsystem_cert_nickname %s #RA subsystem cert nickname",
- x_ra_subsystem_cert_nickname);
-
- parser.addOption("-subsystem_name %s #RA subsystem name",
- x_subsystem_name);
-
- // and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
-
- if (unmatched != null) {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- // set variables
- cs_hostname = x_cs_hostname.value;
- cs_port = x_cs_port.value;
- cs_clientauth_port = x_cs_clientauth_port.value;
-
- sd_hostname = x_sd_hostname.value;
- sd_ssl_port = x_sd_ssl_port.value;
- sd_agent_port = x_sd_agent_port.value;
- sd_admin_port = x_sd_admin_port.value;
- sd_admin_name = x_sd_admin_name.value;
- sd_admin_password = x_sd_admin_password.value;
-
- ca_hostname = x_ca_hostname.value;
- ca_port = x_ca_port.value;
- ca_ssl_port = x_ca_ssl_port.value;
- ca_admin_port = x_ca_admin_port.value;
-
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- pin = x_preop_pin.value;
- domain_name = x_domain_name.value;
-
- admin_user = x_admin_user.value;
- admin_email = x_admin_email.value;
- admin_password = x_admin_password.value;
- agent_name = x_agent_name.value;
-
- key_size = x_key_size.value;
- key_type = x_key_type.value;
- token_name = x_token_name.value;
- token_pwd = x_token_pwd.value;
-
- agent_key_size = x_agent_key_size.value;
- agent_key_type = x_agent_key_type.value;
- agent_cert_subject = x_agent_cert_subject.value;
-
- ra_server_cert_subject_name = x_ra_server_cert_subject_name.value;
- ra_server_cert_nickname = x_ra_server_cert_nickname.value;
- ra_subsystem_cert_subject_name = x_ra_subsystem_cert_subject_name.value;
- ra_subsystem_cert_nickname = x_ra_subsystem_cert_nickname.value;
-
- subsystem_name = x_subsystem_name.value;
-
- boolean st = ca.ConfigureRAInstance();
-
- if (!st) {
- System.out.println("ERROR: unable to create RA");
- System.exit(-1);
- }
-
- System.out.println("Certificate System - RA Instance Configured");
- System.exit(0);
-
- }
+ String query_string_2 = "p=3" +
+ "&subsystem=RA" +
+ "&session_id=" + ra_session_id +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
+
+ // parse xml - no parsing
+
+ return true;
+
+ }
+
+ public boolean SubsystemPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ sleep_time();
+ String query_string = "p=3" +
+ "&choice=newsubsystem" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+
+ // CA choice panel
+ query_string = "p=4" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean DBPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ // SQL LITE PANEL
+
+ String query_string = "p=5" + "&op=next" + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean TokenChoicePanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ ////////////////////////////////////////////////////////
+ String query_string = null;
+
+ // Software Token
+ if(token_name.equalsIgnoreCase("internal"))
+ {
+ query_string = "p=6" +
+ "&choice=" +
+ URLEncoder.encode("NSS Certificate DB") +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+ }
+ // HSM
+ else
+ {
+ // login to hsm first
+ query_string = "p=7" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // choice with token name now
+ query_string = "p=6" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ }
+
+
+ return true;
+ }
+
+ public boolean KeyPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String query_string = "p=8" +
+ "&keytype=" + key_type +
+ "&choice=default"+
+ "&custom_size=" + key_size +
+ "&sslserver_keytype=" + key_type +
+ "&sslserver_choice=custom" +
+ "&sslserver_custom_size=" + key_size +
+ "&subsystem_keytype=" + key_type +
+ "&subsystem_choice=custom" +
+ "&subsystem_custom_size=" + key_size +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertSubjectPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+
+ String query_string = "p=9" +
+ "&sslserver=" +
+ URLEncoder.encode(ra_server_cert_subject_name) +
+ "&sslserver_nick=" +
+ URLEncoder.encode(ra_server_cert_nickname) +
+ "&subsystem=" +
+ URLEncoder.encode(ra_subsystem_cert_subject_name) +
+ "&subsystem_nick=" +
+ URLEncoder.encode(ra_subsystem_cert_nickname) +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertificatePanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String query_string = "p=10" +
+ "&sslserver=" +
+ "&sslserver_cc=" +
+ "&subsystem=" +
+ "&subsystem_cc=" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean AdminCertReqPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String admin_cert_request = null;
+
+ requestor_name = "RA-" + cs_hostname + "-" + cs_clientauth_port;
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.setTransportCert(null);
+ cCrypt.setDualKey(false);
+ cCrypt.loginDB();
+
+ String crmf_request = cCrypt.generateCRMFrequest();
+
+ if(crmf_request == null)
+ {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
+ }
+
+ admin_cert_request = crmf_request;
+
+ String query_string = "p=11" +
+ "&uid=" + admin_user +
+ "&name=" +
+ URLEncoder.encode("RA Administrator") +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&display=0" +
+ "&profileId=" + "caAdminCert" +
+ "&cert_request_type=" + "crmf" +
+ "&import=true" +
+ "&uid=" + admin_user +
+ "&clone=0" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&requestor_name=" +
+ URLEncoder.encode( requestor_name ) +
+ "&sessionID=" + ra_session_id +
+ "&auth_hostname=" + ca_hostname +
+ "&auth_port=" + ca_ssl_port +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ admin_serial_number = px.getvalue("serialNumber");
+
+ return true;
+ }
+
+ public boolean AdminCertImportPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String cert_to_import = null;
+
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "" ;
+
+ // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
+ // whereas RA and TPS use the CA Admin Port associated with
+ // the 'CA choice panel' as invoked from the SubsystemPanel()
+ // which MAY or MAY NOT be the same CA as the CA specified
+ // by the Security Domain.
+ hr = hc.sslConnect(ca_hostname,ca_admin_port,admin_uri,query_string);
+
+ try
+ {
+ // cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("ERROR: failed to retrieve cert");
+ }
+
+ System.out.println("Imported Cert=" + cert_to_import);
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
+
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ if(!st)
+ {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
+ return false;
+ }
+
+ System.out.println("SUCCESS: imported admin user cert");
+
+ String query_string_1 = "p=12" +
+ "&serialNumber=" + admin_serial_number +
+ "&caHost=" +
+ URLEncoder.encode( ca_hostname ) +
+ "&caPort=" + ca_admin_port +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect( cs_hostname, cs_port, wizard_uri ,query_string_1 );
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean ConfigureRAInstance()
+ {
+ // 0. login to cert db
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ // instantiate http client
+ hc = new HTTPClient();
+
+ sleep_time();
+ // 1. Login panel
+ boolean log_st = LoginPanel();
+ if(!log_st)
+ {
+ System.out.println("ERROR: JSESSIONID not found.");
+ System.out.println("ERROR: ConfigureRA: LoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 2. domain panel
+ boolean dom_st = DomainPanel();
+ if(!dom_st)
+ {
+ System.out.println("ERROR: ConfigureRA: DomainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 3. display cert chain panel
+ boolean disp_st = DisplayChainPanel();
+ if(!disp_st)
+ {
+ System.out.println("ERROR: ConfigureRA: DisplayChainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // security domain login panel
+ boolean disp_sd = SecurityDomainLoginPanel();
+ if(!disp_sd)
+ {
+ System.out.println("ERROR: ConfigureRA: SecurityDomainLoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 4. subsystem panel
+ boolean disp_ss = SubsystemPanel();
+ if(!disp_ss)
+ {
+ System.out.println("ERROR: ConfigureRA: SubsystemPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 5. ldap connection panel
+ boolean disp_ldap = DBPanel();
+ if(!disp_ldap)
+ {
+ System.out.println("ERROR: ConfigureRA: DBPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 6. Token Choice Panel
+ boolean disp_token = TokenChoicePanel();
+ if(!disp_token)
+ {
+ System.out.println("ERROR: ConfigureRA: TokenChoicePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 8. Key Panel
+ boolean disp_key = KeyPanel();
+ if(!disp_key)
+ {
+ System.out.println("ERROR: ConfigureRA: KeyPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 9. Cert Subject Panel
+ boolean disp_csubj = CertSubjectPanel();
+ if(!disp_csubj)
+ {
+ System.out.println("ERROR: ConfigureRA: CertSubjectPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 10. Certificate Panel
+ boolean disp_cp = CertificatePanel();
+ if(!disp_cp)
+ {
+ System.out.println("ERROR: ConfigureRA: CertificatePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 11. Admin Cert Req Panel
+ boolean disp_adm = AdminCertReqPanel();
+ if(!disp_adm)
+ {
+ System.out.println("ERROR: ConfigureRA: AdminCertReqPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 12. Admin Cert import Panel
+ boolean disp_im = AdminCertImportPanel();
+ if(!disp_im)
+ {
+ System.out.println("ERROR: ConfigureRA: AdminCertImportPanel() failure");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String args[])
+ {
+ ConfigureRA ca = new ConfigureRA();
+
+ // set variables
+ StringHolder x_cs_hostname = new StringHolder();
+ StringHolder x_cs_port = new StringHolder();
+ StringHolder x_cs_clientauth_port = new StringHolder();
+
+ StringHolder x_sd_hostname = new StringHolder();
+ StringHolder x_sd_ssl_port = new StringHolder();
+ StringHolder x_sd_agent_port = new StringHolder();
+ StringHolder x_sd_admin_port = new StringHolder();
+ StringHolder x_sd_admin_name = new StringHolder();
+ StringHolder x_sd_admin_password = new StringHolder();
+
+ StringHolder x_ca_hostname = new StringHolder();
+ StringHolder x_ca_port = new StringHolder();
+ StringHolder x_ca_ssl_port = new StringHolder();
+ StringHolder x_ca_admin_port = new StringHolder();
+
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_preop_pin = new StringHolder();
+
+ StringHolder x_domain_name = new StringHolder();
+
+ StringHolder x_admin_user = new StringHolder();
+ StringHolder x_admin_email = new StringHolder();
+ StringHolder x_admin_password = new StringHolder();
+
+ // key size
+ StringHolder x_token_name = new StringHolder();
+ StringHolder x_token_pwd = new StringHolder();
+ StringHolder x_key_size = new StringHolder();
+ StringHolder x_key_type = new StringHolder();
+
+ StringHolder x_agent_key_size = new StringHolder();
+ StringHolder x_agent_key_type = new StringHolder();
+ StringHolder x_agent_cert_subject = new StringHolder();
+
+ StringHolder x_agent_name = new StringHolder();
+
+ // ra cert subject name params
+ StringHolder x_ra_server_cert_subject_name = new StringHolder();
+ StringHolder x_ra_server_cert_nickname = new StringHolder();
+ StringHolder x_ra_subsystem_cert_subject_name = new StringHolder();
+ StringHolder x_ra_subsystem_cert_nickname = new StringHolder();
+
+ // subsystemName
+ StringHolder x_subsystem_name = new StringHolder();
+
+
+ // parse the args
+ ArgParser parser = new ArgParser("ConfigureRA");
+
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL port",
+ x_cs_port);
+ parser.addOption ("-cs_clientauth_port %s #CS SSL port",
+ x_cs_clientauth_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+ parser.addOption ("-ca_admin_port %s #CA SSL Admin port",
+ x_ca_admin_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password",
+ x_token_pwd);
+ parser.addOption ("-key_size %s #Key Size",
+ x_key_size);
+ parser.addOption ("-key_type %s #Key type [rsa,ecc]",
+ x_key_type);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption (
+ "-ra_server_cert_subject_name %s #RA server cert subject name",
+ x_ra_server_cert_subject_name);
+ parser.addOption (
+ "-ra_server_cert_nickname %s #RA server cert nickname",
+ x_ra_server_cert_nickname);
+ parser.addOption (
+ "-ra_subsystem_cert_subject_name %s #RA subsystem cert subject name",
+ x_ra_subsystem_cert_subject_name);
+ parser.addOption (
+ "-ra_subsystem_cert_nickname %s #RA subsystem cert nickname",
+ x_ra_subsystem_cert_nickname);
+
+ parser.addOption (
+ "-subsystem_name %s #RA subsystem name",
+ x_subsystem_name);
+
+ // and then match the arguments
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+
+ if(unmatched!=null)
+ {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ // set variables
+ cs_hostname = x_cs_hostname.value;
+ cs_port = x_cs_port.value;
+ cs_clientauth_port = x_cs_clientauth_port.value;
+
+ sd_hostname = x_sd_hostname.value;
+ sd_ssl_port = x_sd_ssl_port.value;
+ sd_agent_port = x_sd_agent_port.value;
+ sd_admin_port = x_sd_admin_port.value;
+ sd_admin_name = x_sd_admin_name.value;
+ sd_admin_password = x_sd_admin_password.value;
+
+ ca_hostname = x_ca_hostname.value;
+ ca_port = x_ca_port.value;
+ ca_ssl_port = x_ca_ssl_port.value;
+ ca_admin_port = x_ca_admin_port.value;
+
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ pin = x_preop_pin.value;
+ domain_name = x_domain_name.value;
+
+ admin_user = x_admin_user.value;
+ admin_email = x_admin_email.value;
+ admin_password = x_admin_password.value;
+ agent_name = x_agent_name.value;
+
+ key_size = x_key_size.value;
+ key_type = x_key_type.value;
+ token_name = x_token_name.value;
+ token_pwd = x_token_pwd.value;
+
+ agent_key_size = x_agent_key_size.value;
+ agent_key_type = x_agent_key_type.value;
+ agent_cert_subject = x_agent_cert_subject.value;
+
+ ra_server_cert_subject_name =
+ x_ra_server_cert_subject_name.value ;
+ ra_server_cert_nickname =
+ x_ra_server_cert_nickname.value ;
+ ra_subsystem_cert_subject_name =
+ x_ra_subsystem_cert_subject_name.value;
+ ra_subsystem_cert_nickname =
+ x_ra_subsystem_cert_nickname.value;
+
+ subsystem_name = x_subsystem_name.value ;
+
+
+
+ boolean st = ca.ConfigureRAInstance();
+
+ if (!st)
+ {
+ System.out.println("ERROR: unable to create RA");
+ System.exit(-1);
+ }
+
+ System.out.println("Certificate System - RA Instance Configured");
+ System.exit(0);
+
+ }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
index dad41eda..93d115fc 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -30,7 +29,8 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureSubCA {
+public class ConfigureSubCA
+{
// global constants
public static final String DEFAULT_KEY_TYPE = "RSA";
@@ -42,7 +42,7 @@ public class ConfigureSubCA {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/ca/admin/console/config/login";
public static String wizard_uri = "/ca/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -68,7 +68,7 @@ public class ConfigureSubCA {
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -153,36 +153,42 @@ public class ConfigureSubCA {
public static String subsystem_name = null;
- // names
+ // names
public static String subca_sign_cert_subject_name = null;
public static String subca_subsystem_cert_subject_name = null;
public static String subca_ocsp_cert_subject_name = null;
public static String subca_server_cert_subject_name = null;
public static String subca_audit_signing_cert_subject_name = null;
- public ConfigureSubCA() {
+ public ConfigureSubCA ()
+ {
// do nothing :)
}
- public void sleep_time() {
- try {
+ public void sleep_time()
+ {
+ try
+ {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- } catch (Exception e) {
+ }
+ catch(Exception e)
+ {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel() {
+ public boolean LoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -190,60 +196,72 @@ public class ConfigureSubCA {
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp != null) {
+ if (temp!=null)
+ {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
+ HTTPClient.j_session_id = temp.substring(0,index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ "p=0&op=next&xml=true");
// parse xml here
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
return st;
}
- public boolean TokenChoicePanel() {
+ public boolean TokenChoicePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- // /////////////////////////////////////////////////////
+ ///////////////////////////////////////////////////////
String query_string = null;
// Software Token
- if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token") + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ if (token_name.equalsIgnoreCase("internal"))
+ {
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode("Internal Key Storage Token") +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
}
// HSM
- else {
+ else
+ {
// login to hsm first
- query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=2" + "&op=next" + "&xml=true" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -254,85 +272,103 @@ public class ConfigureSubCA {
return true;
}
- public boolean DomainPanel() {
+ public boolean DomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
- String query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&sdomainName=" + URLEncoder.encode(domain_name)
- + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&sdomainName="+
+ URLEncoder.encode(domain_name) +
+ "&choice=existingdomain"+
+ "&p=3" +
+ "&op=next" +
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
- String query_string_1 = "p=4" + "&op=next" + "&xml=true";
+ String query_string_1 = "p=4" +
+ "&op=next" +
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string_1);
return true;
}
- public boolean SecurityDomainLoginPanel() {
+ public boolean SecurityDomainLoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String subca_url = "https://" + cs_hostname + ":" + cs_port
- + "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA";
- String query_string = "url=" + URLEncoder.encode(subca_url);
+ String subca_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ca/admin/console/config/wizard" +
+ "?p=5&subsystem=CA" ;
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
+ String query_string = "url=" + URLEncoder.encode(subca_url);
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(subca_url);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(subca_url) ;
+
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
// get session id from security domain
String subca_session_id = hr.getContentValue("header.session_id");
String subca_url_1 = hr.getContentValue("header.url");
- System.out.println("SUBCA_SESSION_ID=" + subca_session_id);
- System.out.println("SUBCA_URL=" + subca_url_1);
+ System.out.println("SUBCA_SESSION_ID=" + subca_session_id );
+ System.out.println("SUBCA_URL=" + subca_url_1 );
// use session id to connect back to subCA
- String query_string_2 = "p=5" + "&subsystem=CA" + "&session_id="
- + subca_session_id + "&xml=true";
+ String query_string_2 = "p=5" +
+ "&subsystem=CA" +
+ "&session_id=" + subca_session_id +
+ "&xml=true" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
return true;
}
- public boolean DisplayChainPanel() {
+ public boolean DisplayChainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=5" + "&op=next" + "&xml=true"
- + "&choice=newsubsystem" + "&subsystemName="
- + URLEncoder.encode(subsystem_name) + "&subsystemName="
- + URLEncoder.encode(subsystem_name) + "&urls=0";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=5" + "&op=next" + "&xml=true" +
+ "&choice=newsubsystem" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&urls=0" ;
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -341,44 +377,50 @@ public class ConfigureSubCA {
return true;
}
- public boolean HierarchyPanel() {
+ public boolean HierarchyPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=8" + "&op=next" + "&xml=true" + "&choice=join";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=8" + "&op=next" + "&xml=true" +
+ "&choice=join" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
+
return true;
}
- public boolean LdapConnectionPanel() {
+ public boolean LdapConnectionPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=9" + "&op=next" + "&xml=true" + "&host="
- + URLEncoder.encode(ldap_host) + "&port="
- + URLEncoder.encode(ldap_port) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true") ? "&secureConn=on" : "")
- + (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "")
- + (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=9" + "&op=next" + "&xml=true" +
+ "&host=" + URLEncoder.encode(ldap_host) +
+ "&port=" + URLEncoder.encode(ldap_port) +
+ "&basedn=" + URLEncoder.encode(base_dn) +
+ "&database=" + URLEncoder.encode(db_name) +
+ "&binddn=" + URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" + URLEncoder.encode(bind_password) +
+ "&display=" + URLEncoder.encode("$displayStr") +
+ (secure_conn.equals("true")? "&secureConn=on": "") +
+ (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
+ (remove_data.equals("true")? "&removeData=true": "");
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -388,7 +430,8 @@ public class ConfigureSubCA {
return true;
}
- public boolean KeyPanel() {
+ public boolean KeyPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -396,76 +439,53 @@ public class ConfigureSubCA {
ArrayList<String> al = null;
String query_string = "p=10" + "&op=next" + "&xml=true"
- + "&subsystem_custom_size="
- + subsystem_key_size
- + "&subsystem_custom_curvename="
- + subsystem_key_curvename
- + "&subsystem_keytype="
- + subsystem_key_type
- + "&subsystem_choice=custom"
- + "&sslserver_custom_size="
- + sslserver_key_size
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename
- + "&sslserver_keytype="
- + sslserver_key_type
- + "&sslserver_choice=custom"
- + "&signing_custom_size="
- + signing_key_size
- + "&signing_custom_curvename="
- + signing_key_curvename
- + "&signing_keytype="
- + signing_key_type
- + "&signing_choice=custom"
- + "&signing_keyalgorithm="
- + key_algorithm
- + "&signing_signingalgorithm="
- + signing_signingalgorithm
- + "&ocsp_signing_custom_size="
- + ocsp_signing_key_size
- + "&ocsp_signing_custom_curvename="
- + ocsp_signing_key_curvename
- + "&ocsp_signing_keytype="
- + ocsp_signing_key_type
- + "&ocsp_signing_choice=custom"
- + "&ocsp_signing_signingalgorithm="
- + ocsp_signing_signingalgorithm
- + "&audit_signing_custom_size="
- + audit_signing_key_size
- + "&audit_signing_custom_curvename="
- + audit_signing_key_curvename
- + "&audit_signing_keytype="
- + audit_signing_key_type
- + "&audit_signing_choice=custom"
- + "&custom_size="
- + key_size
- + "&custom_curvename="
- + key_curvename
- + "&keytype="
- + key_type
- + "&choice=custom"
- + "&signingalgorithm="
- + signing_algorithm
- + "&keyalgorithm="
- + key_algorithm;
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ + "&subsystem_custom_size=" + subsystem_key_size
+ + "&subsystem_custom_curvename=" + subsystem_key_curvename
+ + "&subsystem_keytype=" + subsystem_key_type
+ + "&subsystem_choice=custom"
+ + "&sslserver_custom_size=" + sslserver_key_size
+ + "&sslserver_custom_curvename=" + sslserver_key_curvename
+ + "&sslserver_keytype=" + sslserver_key_type
+ + "&sslserver_choice=custom"
+ + "&signing_custom_size=" + signing_key_size
+ + "&signing_custom_curvename=" + signing_key_curvename
+ + "&signing_keytype=" + signing_key_type
+ + "&signing_choice=custom"
+ + "&signing_keyalgorithm=" + key_algorithm
+ + "&signing_signingalgorithm=" + signing_signingalgorithm
+ + "&ocsp_signing_custom_size=" + ocsp_signing_key_size
+ + "&ocsp_signing_custom_curvename=" + ocsp_signing_key_curvename
+ + "&ocsp_signing_keytype=" + ocsp_signing_key_type
+ + "&ocsp_signing_choice=custom"
+ + "&ocsp_signing_signingalgorithm=" + ocsp_signing_signingalgorithm
+ + "&audit_signing_custom_size=" + audit_signing_key_size
+ + "&audit_signing_custom_curvename=" + audit_signing_key_curvename
+ + "&audit_signing_keytype=" + audit_signing_key_type
+ + "&audit_signing_choice=custom"
+ + "&custom_size=" + key_size
+ + "&custom_curvename=" + key_curvename
+ + "&keytype=" + key_type
+ + "&choice=custom"
+ + "&signingalgorithm=" + signing_algorithm
+ + "&keyalgorithm=" + key_algorithm;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair", "DN");
+
+ al = px.constructValueList("CertReqPair","DN");
// get ca cert subject name
if (al != null) {
- for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
- if (temp.indexOf("Certificate Authority") > 0) {
+ for (int i=0; i < al.size(); i++) {
+ String temp = al.get(i);
+ if (temp.indexOf("Certificate Authority") > 0 ) {
ca_cert_name = temp;
- } else if (temp.indexOf("OCSP Signing Certificate") > 0) {
+ } else if (temp.indexOf("OCSP Signing Certificate") > 0 ) {
ocsp_cert_name = temp;
- } else if (temp.indexOf("Subsystem Certificate") > 0) {
+ } else if (temp.indexOf("Subsystem Certificate") > 0 ) {
ca_subsystem_cert_name = temp;
} else if (temp.indexOf("Audit Signing Certificate") > 0) {
ca_audit_signing_cert_name = temp;
@@ -474,18 +494,19 @@ public class ConfigureSubCA {
}
}
}
-
+
System.out.println("default: ca_cert_name=" + ca_cert_name);
System.out.println("default: ocsp_cert_name=" + ocsp_cert_name);
- System.out.println("default: ca_subsystem_cert_name="
- + ca_subsystem_cert_name);
+ System.out.println("default: ca_subsystem_cert_name=" +
+ ca_subsystem_cert_name);
System.out.println("default: server_cert_name=" + server_cert_name);
- System.out.println("default: ca_audit_signing_cert_name="
- + ca_audit_signing_cert_name);
+ System.out.println("default: ca_audit_signing_cert_name=" +
+ ca_audit_signing_cert_name);
return true;
}
- public boolean CertSubjectPanel() {
+ public boolean CertSubjectPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -494,85 +515,89 @@ public class ConfigureSubCA {
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
- String query_string = "p=11" + "&op=next" + "&xml=true" + "&signing="
- + URLEncoder.encode(subca_sign_cert_subject_name)
- + "&ocsp_signing="
- + URLEncoder.encode(subca_ocsp_cert_subject_name)
- + "&sslserver="
- + URLEncoder.encode(subca_server_cert_subject_name)
- + "&subsystem="
- + URLEncoder.encode(subca_subsystem_cert_subject_name)
- + "&audit_signing="
- + URLEncoder.encode(subca_audit_signing_cert_subject_name)
- + "&urls=0" + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=11" + "&op=next" + "&xml=true" +
+ "&signing=" +
+ URLEncoder.encode(subca_sign_cert_subject_name) +
+ "&ocsp_signing=" +
+ URLEncoder.encode(subca_ocsp_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(subca_server_cert_subject_name) +
+ "&subsystem=" +
+ URLEncoder.encode(subca_subsystem_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(subca_audit_signing_cert_subject_name) +
+ "&urls=0" +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair", "Request");
- cert_list = px.constructValueList("CertReqPair", "Certificate");
- dn_list = px.constructValueList("CertReqPair", "Nickname");
+
+ req_list = px.constructValueList("CertReqPair","Request");
+ cert_list = px.constructValueList("CertReqPair","Certificate");
+ dn_list = px.constructValueList("CertReqPair","Nickname");
System.out.println("req_list_size=" + req_list.size());
System.out.println("cert_list_size=" + cert_list.size());
System.out.println("dn_list_size=" + dn_list.size());
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("caSigningCert") >= 0) {
- ca_cert_req = req_list.get(i);
- ca_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("ocspSigningCert") >= 0) {
- ocsp_cert_req = req_list.get(i);
- ocsp_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("subsystemCert") >= 0) {
- ca_subsystem_cert_req = req_list.get(i);
- ca_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >= 0) {
- ca_audit_signing_cert_req = req_list.get(i);
- ca_audit_signing_cert_cert = cert_list.get(i);
+ for (int i=0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("caSigningCert") >= 0 ) {
+ ca_cert_req = req_list.get(i);
+ ca_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("ocspSigningCert") >= 0 ) {
+ ocsp_cert_req = req_list.get(i);
+ ocsp_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("subsystemCert") >= 0 ) {
+ ca_subsystem_cert_req = req_list.get(i);
+ ca_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >=0) {
+ ca_audit_signing_cert_req = req_list.get(i);
+ ca_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
System.out.println("ca_cert_name=" + subca_sign_cert_subject_name);
System.out.println("ocsp_cert_name=" + subca_ocsp_cert_subject_name);
- System.out.println("ca_subsystem_cert_name="
- + subca_subsystem_cert_subject_name);
- System.out
- .println("server_cert_name=" + subca_server_cert_subject_name);
- System.out.println("audit_signing_cert_name="
- + subca_audit_signing_cert_subject_name);
+ System.out.println("ca_subsystem_cert_name=" +
+ subca_subsystem_cert_subject_name);
+ System.out.println("server_cert_name=" +
+ subca_server_cert_subject_name);
+ System.out.println("audit_signing_cert_name=" +
+ subca_audit_signing_cert_subject_name);
System.out.println("ca_cert_req=" + ca_cert_req);
System.out.println("ocsp_cert_req=" + ocsp_cert_req);
System.out.println("ca_subsystem_cert_req=" + ca_subsystem_cert_req);
System.out.println("server_cert_req=" + server_cert_req);
- System.out.println("ca_audit_siging_cert_req="
- + ca_audit_signing_cert_req);
+ System.out.println("ca_audit_siging_cert_req=" +
+ ca_audit_signing_cert_req);
System.out.println("ca_cert_cert=" + ca_cert_cert);
System.out.println("ocsp_cert_cert=" + ocsp_cert_cert);
System.out.println("ca_subsystem_cert_cert=" + ca_subsystem_cert_cert);
System.out.println("server_cert_cert=" + server_cert_cert);
- System.out.println("ca_audit_signing_cert_cert="
- + ca_audit_signing_cert_cert);
+ System.out.println("ca_audit_signing_cert_cert=" +
+ ca_audit_signing_cert_cert);
return true;
}
- public boolean CertificatePanel() {
+ public boolean CertificatePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -582,44 +607,55 @@ public class ConfigureSubCA {
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
- String query_string = "p=12" + "&op=next" + "&xml=true" + "&signing="
- + URLEncoder.encode(ca_cert_cert) + "&signing_cc="
- + "&ocsp_signing=" + URLEncoder.encode(ocsp_cert_cert)
- + "&ocsp_signing_cc=" + "&sslserver="
- + URLEncoder.encode(server_cert_cert) + "&sslserver_cc="
- + "&subsystem=" + URLEncoder.encode(ca_subsystem_cert_cert)
- + "&subsystem_cc=" + "&audit_signing="
- + URLEncoder.encode(ca_audit_signing_cert_cert)
- + "&audit_signing_cc=" + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=12" + "&op=next" + "&xml=true" +
+ "&signing=" +
+ URLEncoder.encode(ca_cert_cert) +
+ "&signing_cc=" +
+ "&ocsp_signing=" +
+ URLEncoder.encode(ocsp_cert_cert) +
+ "&ocsp_signing_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&subsystem=" +
+ URLEncoder.encode(ca_subsystem_cert_cert) +
+ "&subsystem_cc=" +
+ "&audit_signing=" +
+ URLEncoder.encode(ca_audit_signing_cert_cert) +
+ "&audit_signing_cc=" +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel() {
+ public boolean BackupPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd="
- + URLEncoder.encode(backup_pwd) + "&__pwdagain="
- + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=13" + "&op=next" + "&xml=true" +
+ "&choice=backupkey" +
+ "&__pwd=" + URLEncoder.encode(backup_pwd) +
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
@@ -630,7 +666,7 @@ public class ConfigureSubCA {
ParseXML px = new ParseXML();
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=15&op=next&xml=true");
+ "p=15&op=next&xml=true");
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -638,24 +674,28 @@ public class ConfigureSubCA {
return true;
} catch (Exception e) {
- System.out.println("Exception in ImportCACertPanel(): "
- + e.toString());
+ System.out.println("Exception in ImportCACertPanel(): " + e.toString());
e.printStackTrace();
return false;
}
}
- public boolean AdminCertReqPanel() {
+ public boolean AdminCertReqPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
+
String cert_subject = "CN=" + "subca-" + admin_user;
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.setTransportCert(null);
@@ -665,68 +705,80 @@ public class ConfigureSubCA {
String crmf_request = cCrypt.generateCRMFrequest();
if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
}
admin_cert_request = crmf_request;
- String query_string = "p=16" + "&op=next" + "&xml=true" + "&uid="
- + admin_user + "&name=" + URLEncoder.encode(agent_name)
- + "&email=" + URLEncoder.encode(admin_email) + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&cert_request="
- + URLEncoder.encode(admin_cert_request) + "&display="
- + URLEncoder.encode("$displayStr") + "&profileId="
- + "caAdminCert" + "&cert_request_type=" + "crmf"
- + "&import=true" + "&uid=" + admin_user + "&securitydomain="
- + URLEncoder.encode(domain_name) + "&subject="
- + URLEncoder.encode(agent_cert_subject) + "";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=16" + "&op=next" + "&xml=true" +
+ "&uid=" + admin_user +
+ "&name=" + URLEncoder.encode( agent_name ) +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&display=" + URLEncoder.encode("$displayStr") +
+ "&profileId=" + "caAdminCert" +
+ "&cert_request_type=" + "crmf" +
+ "&import=true" +
+ "&uid=" + admin_user +
+ "&securitydomain=" +
+ URLEncoder.encode( domain_name ) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel() {
+ public boolean AdminCertImportPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true" + "";
-
- hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string);
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,admin_uri,query_string);
+
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import = OSUtil.BtoA(hr.getResponseData());
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
- if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ if (!st)
+ {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -735,24 +787,28 @@ public class ConfigureSubCA {
return true;
}
- public boolean UpdateDomainPanel() {
+ public boolean UpdateDomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=17" + "&serialNumber=" + admin_serial_number
- + "&caHost=" + URLEncoder.encode(sd_hostname) + "&caPort="
- + URLEncoder.encode(sd_admin_port) + "&importCert=" + "true"
- + "&op=next" + "&xml=true" + "";
+ String query_string = "p=17" +
+ "&serialNumber=" + admin_serial_number +
+ "&caHost=" + URLEncoder.encode(sd_hostname) +
+ "&caPort=" + URLEncoder.encode(sd_admin_port) +
+ "&importCert=" + "true" +
+ "&op=next" + "&xml=true" +
+ "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
String caHost = px.getvalue("host");
String caPort = px.getvalue("port");
String systemType = px.getvalue("systemType");
@@ -760,14 +816,18 @@ public class ConfigureSubCA {
System.out.println("caHost=" + caHost);
System.out.println("caPort=" + caPort);
System.out.println("systemType=" + systemType);
-
+
return true;
}
- public boolean ConfigureSubCAInstance() {
+ public boolean ConfigureSubCAInstance()
+ {
// 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
@@ -787,8 +847,7 @@ public class ConfigureSubCA {
// 1. Token Choice Panel
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out
- .println("ERROR: ConfigureSubCA: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: TokenChoicePanel() failure");
return false;
}
@@ -804,8 +863,7 @@ public class ConfigureSubCA {
// 3. domain panel
boolean sd_st = SecurityDomainLoginPanel();
if (!sd_st) {
- System.out
- .println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
return false;
}
@@ -813,8 +871,7 @@ public class ConfigureSubCA {
// 4. display cert chain panel
boolean disp_st = DisplayChainPanel();
if (!disp_st) {
- System.out
- .println("ERROR: ConfigureSubCA: DisplayChainPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: DisplayChainPanel() failure");
return false;
}
@@ -822,8 +879,7 @@ public class ConfigureSubCA {
// 6. hierarchy panel
boolean disp_h = HierarchyPanel();
if (!disp_h) {
- System.out
- .println("ERROR: ConfigureSubCA: HierarchyPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: HierarchyPanel() failure");
return false;
}
@@ -831,8 +887,7 @@ public class ConfigureSubCA {
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureSubCA: LdapConnectionPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: LdapConnectionPanel() failure");
return false;
}
@@ -849,8 +904,7 @@ public class ConfigureSubCA {
// 11. Cert Subject Panel
boolean disp_csubj = CertSubjectPanel();
if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureSubCA: CertSubjectPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: CertSubjectPanel() failure");
return false;
}
@@ -858,8 +912,7 @@ public class ConfigureSubCA {
// 12. Certificate Panel
boolean disp_cp = CertificatePanel();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureSubCA: CertificatePanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: CertificatePanel() failure");
return false;
}
@@ -875,8 +928,7 @@ public class ConfigureSubCA {
// 15. Import CA Certificate Panel
boolean disp_cert = ImportCACertPanel();
if (!disp_cert) {
- System.out
- .println("ERROR: ConfigureSubCA: ImportCACertPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: ImportCACertPanel() failure");
return false;
}
@@ -884,16 +936,14 @@ public class ConfigureSubCA {
// 16. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureSubCA: AdminCertReqPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: AdminCertReqPanel() failure");
return false;
}
sleep_time();
boolean disp_im = AdminCertImportPanel();
if (!disp_im) {
- System.out
- .println("ERROR: ConfigureSubCA: AdminCertImportPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: AdminCertImportPanel() failure");
return false;
}
@@ -901,8 +951,7 @@ public class ConfigureSubCA {
// 17. Update Domain Panel
boolean disp_ud = UpdateDomainPanel();
if (!disp_ud) {
- System.out
- .println("ERROR: ConfigureSubCA: UpdateDomainPanel() failure");
+ System.out.println("ERROR: ConfigureSubCA: UpdateDomainPanel() failure");
return false;
}
@@ -917,7 +966,8 @@ public class ConfigureSubCA {
}
}
- public static void main(String args[]) {
+ public static void main(String args[])
+ {
ConfigureSubCA ca = new ConfigureSubCA();
// set variables
@@ -945,7 +995,7 @@ public class ConfigureSubCA {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -974,7 +1024,7 @@ public class ConfigureSubCA {
StringHolder x_ocsp_signing_key_type = new StringHolder();
StringHolder x_ocsp_signing_key_curvename = new StringHolder();
StringHolder x_ocsp_signing_signingalgorithm = new StringHolder();
-
+
// key properties (custom - audit_signing)
StringHolder x_audit_signing_key_size = new StringHolder();
StringHolder x_audit_signing_key_type = new StringHolder();
@@ -1008,180 +1058,142 @@ public class ConfigureSubCA {
StringHolder x_subca_subsystem_cert_subject_name = new StringHolder();
StringHolder x_subca_ocsp_cert_subject_name = new StringHolder();
StringHolder x_subca_server_cert_subject_name = new StringHolder();
- StringHolder x_subca_audit_signing_cert_subject_name = new StringHolder();
+ StringHolder x_subca_audit_signing_cert_subject_name = new StringHolder();
// parse the args
ArgParser parser = new ArgParser("ConfigureSubCA");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL port", x_cs_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain admin name",
- x_sd_admin_name);
- parser.addOption(
- "-sd_admin_password %s #Security Domain admin password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL port", x_ca_ssl_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
- parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption(
- "-secure_conn %s #use ldaps port (optional, default is false)",
- x_secure_conn);
- parser.addOption(
- "-remove_data %s #remove existing data under base_dn (optional, default is false) ",
- x_remove_data);
- parser.addOption(
- "-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)",
- x_clone_start_tls);
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL port",
+ x_cs_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain admin name",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain admin password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption ("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption ("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption ("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption ("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption ("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption(
- "-key_type %s #Key type [RSA,ECC] (optional, default is RSA)",
- x_key_type);
- parser.addOption(
- "-key_size %s #Key Size (optional, for RSA default is 2048)",
- x_key_size);
- parser.addOption(
- "-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)",
- x_key_curvename);
- parser.addOption(
- "-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)",
- x_key_algorithm);
- parser.addOption(
- "-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)",
- x_signing_algorithm);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+ parser.addOption("-key_algorithm %s #Key algorithm of the CA certificate (optional, default is SHA256withRSA for RSA and SHA256withEC for ECC)", x_key_algorithm);
+ parser.addOption("-signing_algorithm %s #Signing algorithm (optional, default is key_algorithm)", x_signing_algorithm);
// key and algorithm options for signing certificate (overrides default)
- parser.addOption(
- "-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_signing_key_type);
- parser.addOption(
- "-signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_signing_key_size);
- parser.addOption(
- "-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_signing_key_curvename);
- parser.addOption(
- "-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)",
- x_signing_signingalgorithm);
-
- // key and algorithm options for ocsp_signing certificate (overrides
- // default)
- parser.addOption(
- "-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_ocsp_signing_key_type);
- parser.addOption(
- "-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_ocsp_signing_key_size);
- parser.addOption(
- "-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_ocsp_signing_key_curvename);
- parser.addOption(
- "-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)",
- x_ocsp_signing_signingalgorithm);
-
- // key and algorithm options for audit_signing certificate (overrides
- // default)
- parser.addOption(
- "-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_audit_signing_key_type);
- parser.addOption(
- "-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_audit_signing_key_size);
- parser.addOption(
- "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides
- // default)
- parser.addOption(
- "-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_subsystem_key_type);
- parser.addOption(
- "-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_subsystem_key_size);
- parser.addOption(
- "-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides
- // default)
- parser.addOption(
- "-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_sslserver_key_type);
- parser.addOption(
- "-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_sslserver_key_size);
- parser.addOption(
- "-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_sslserver_key_curvename);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional - required for HSM)",
- x_token_pwd);
-
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
-
- parser.addOption("-backup_pwd %s #PKCS12 backup password", x_backup_pwd);
-
- parser.addOption("-subsystem_name %s #Subsystem name", x_subsystem_name);
-
- parser.addOption(
- "-subca_sign_cert_subject_name %s #subCA cert subject name",
- x_subca_sign_cert_subject_name);
- parser.addOption(
- "-subca_subsystem_cert_subject_name %s #subCA subsystem cert subject name",
- x_subca_subsystem_cert_subject_name);
- parser.addOption(
- "-subca_ocsp_cert_subject_name %s #subCA ocsp cert subject name",
- x_subca_ocsp_cert_subject_name);
- parser.addOption(
- "-subca_server_cert_subject_name %s #subCA server cert subject name",
- x_subca_server_cert_subject_name);
- parser.addOption(
+ parser.addOption("-signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_signing_key_type);
+ parser.addOption("-signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_signing_key_size);
+ parser.addOption("-signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_signing_key_curvename);
+ parser.addOption("-signing_signingalgorithm %s #Algorithm used be CA cert to sign objects (optional, default is signing_algorithm)", x_signing_signingalgorithm);
+
+ // key and algorithm options for ocsp_signing certificate (overrides default)
+ parser.addOption("-ocsp_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_ocsp_signing_key_type);
+ parser.addOption("-ocsp_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_ocsp_signing_key_size);
+ parser.addOption("-ocsp_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_ocsp_signing_key_curvename);
+ parser.addOption("-ocsp_signing_signingalgorithm %s #Algorithm used by the OCSP signing cert to sign objects (optional, default is signing_algorithm)", x_ocsp_signing_signingalgorithm);
+
+ // key and algorithm options for audit_signing certificate (overrides default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password (optional - required for HSM)",
+ x_token_pwd);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption ("-backup_pwd %s #PKCS12 backup password",
+ x_backup_pwd);
+
+ parser.addOption ("-subsystem_name %s #Subsystem name",
+ x_subsystem_name);
+
+ parser.addOption (
+ "-subca_sign_cert_subject_name %s #subCA cert subject name",
+ x_subca_sign_cert_subject_name);
+ parser.addOption (
+ "-subca_subsystem_cert_subject_name %s #subCA subsystem cert subject name",
+ x_subca_subsystem_cert_subject_name);
+ parser.addOption (
+ "-subca_ocsp_cert_subject_name %s #subCA ocsp cert subject name",
+ x_subca_ocsp_cert_subject_name);
+ parser.addOption (
+ "-subca_server_cert_subject_name %s #subCA server cert subject name",
+ x_subca_server_cert_subject_name);
+ parser.addOption(
"-subca_audit_signing_cert_subject_name %s #CA audit signing cert subject name",
x_subca_audit_signing_cert_subject_name);
// and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched != null) {
+ if (unmatched!=null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1224,49 +1236,34 @@ public class ConfigureSubCA {
key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE);
signing_key_type = set_default(x_signing_key_type.value, key_type);
- ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value,
- key_type);
- audit_signing_key_type = set_default(x_audit_signing_key_type.value,
- key_type);
+ ocsp_signing_key_type = set_default(x_ocsp_signing_key_type.value, key_type);
+ audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type);
subsystem_key_type = set_default(x_subsystem_key_type.value, key_type);
sslserver_key_type = set_default(x_sslserver_key_type.value, key_type);
key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE);
signing_key_size = set_default(x_signing_key_size.value, key_size);
- ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value,
- key_size);
- audit_signing_key_size = set_default(x_audit_signing_key_size.value,
- key_size);
+ ocsp_signing_key_size = set_default(x_ocsp_signing_key_size.value, key_size);
+ audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size);
subsystem_key_size = set_default(x_subsystem_key_size.value, key_size);
sslserver_key_size = set_default(x_sslserver_key_size.value, key_size);
- key_curvename = set_default(x_key_curvename.value,
- DEFAULT_KEY_CURVENAME);
- signing_key_curvename = set_default(x_signing_key_curvename.value,
- key_curvename);
- ocsp_signing_key_curvename = set_default(
- x_ocsp_signing_key_curvename.value, key_curvename);
- audit_signing_key_curvename = set_default(
- x_audit_signing_key_curvename.value, key_curvename);
- subsystem_key_curvename = set_default(x_subsystem_key_curvename.value,
- key_curvename);
- sslserver_key_curvename = set_default(x_sslserver_key_curvename.value,
- key_curvename);
+ key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME);
+ signing_key_curvename = set_default(x_signing_key_curvename.value, key_curvename);
+ ocsp_signing_key_curvename = set_default(x_ocsp_signing_key_curvename.value, key_curvename);
+ audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename);
+ subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename);
+ sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename);
if (signing_key_type.equalsIgnoreCase("RSA")) {
- key_algorithm = set_default(x_key_algorithm.value,
- DEFAULT_KEY_ALGORITHM_RSA);
+ key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_RSA);
} else {
- key_algorithm = set_default(x_key_algorithm.value,
- DEFAULT_KEY_ALGORITHM_ECC);
+ key_algorithm = set_default(x_key_algorithm.value, DEFAULT_KEY_ALGORITHM_ECC);
}
- signing_algorithm = set_default(x_signing_algorithm.value,
- key_algorithm);
- signing_signingalgorithm = set_default(
- x_signing_signingalgorithm.value, signing_algorithm);
- ocsp_signing_signingalgorithm = set_default(
- x_ocsp_signing_signingalgorithm.value, signing_algorithm);
+ signing_algorithm = set_default(x_signing_algorithm.value, key_algorithm);
+ signing_signingalgorithm = set_default(x_signing_signingalgorithm.value, signing_algorithm);
+ ocsp_signing_signingalgorithm = set_default(x_ocsp_signing_signingalgorithm.value, signing_algorithm);
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
@@ -1277,24 +1274,24 @@ public class ConfigureSubCA {
backup_pwd = x_backup_pwd.value;
subsystem_name = x_subsystem_name.value;
-
- subca_sign_cert_subject_name = x_subca_sign_cert_subject_name.value;
- subca_subsystem_cert_subject_name = x_subca_subsystem_cert_subject_name.value;
- subca_ocsp_cert_subject_name = x_subca_ocsp_cert_subject_name.value;
- subca_server_cert_subject_name = x_subca_server_cert_subject_name.value;
+
+ subca_sign_cert_subject_name = x_subca_sign_cert_subject_name.value ;
+ subca_subsystem_cert_subject_name =
+ x_subca_subsystem_cert_subject_name.value;
+ subca_ocsp_cert_subject_name = x_subca_ocsp_cert_subject_name.value ;
+ subca_server_cert_subject_name = x_subca_server_cert_subject_name.value ;
subca_audit_signing_cert_subject_name = x_subca_audit_signing_cert_subject_name.value;
boolean st = ca.ConfigureSubCAInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create Subordinate CA");
System.exit(-1);
}
-
- System.out
- .println("Certificate System - Subordinate CA Instance Configured.");
+
+ System.out.println("Certificate System - Subordinate CA Instance Configured.");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
index acc9193c..d89fb5dd 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -39,7 +38,8 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureTKS {
+public class ConfigureTKS
+{
public static final String DEFAULT_KEY_TYPE = "RSA";
public static final String DEFAULT_KEY_SIZE = "2048";
@@ -48,7 +48,7 @@ public class ConfigureTKS {
// define global variables
public static HTTPClient hc = null;
-
+
public static String login_uri = "/tks/admin/console/config/login";
public static String wizard_uri = "/tks/admin/console/config/wizard";
public static String admin_uri = "/ca/admin/ca/getBySerial";
@@ -74,7 +74,7 @@ public class ConfigureTKS {
public static String client_certdb_dir = null;
public static String client_certdb_pwd = null;
- // Login Panel
+ // Login Panel
public static String pin = null;
public static String domain_name = null;
@@ -132,38 +132,41 @@ public class ConfigureTKS {
public static String tks_audit_signing_cert_req = null;
public static String tks_audit_signing_cert_pp = null;
public static String tks_audit_signing_cert_cert = null;
-
+
public static String backup_pwd = null;
public static String backup_fname = null;
- // names
+ // names
public static String tks_subsystem_cert_subject_name = null;
public static String tks_server_cert_subject_name = null;
public static String subsystem_name = null;
public static String tks_audit_signing_cert_subject_name = null;
- public ConfigureTKS() {
+ public ConfigureTKS ()
+ {
// do nothing :)
}
- public void sleep_time() {
+ public void sleep_time()
+ {
try {
System.out.println("Sleeping for 5 secs..");
Thread.sleep(5000);
- } catch (Exception e) {
+ } catch(Exception e) {
System.out.println("ERROR: sleep problem");
}
}
- public boolean LoginPanel() {
+ public boolean LoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
System.out.println("xml returned: " + hr.getHTML());
// parse xml here - nothing to parse
@@ -171,26 +174,28 @@ public class ConfigureTKS {
// get cookie
String temp = hr.getCookieValue("JSESSIONID");
- if (temp != null) {
+ if (temp!=null) {
int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
+ HTTPClient.j_session_id = temp.substring(0,index);
st = true;
}
hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ "p=0&op=next&xml=true");
// parse xml here
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
return st;
}
- public boolean TokenChoicePanel() {
+ public boolean TokenChoicePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -200,9 +205,11 @@ public class ConfigureTKS {
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode("Internal Key Storage Token") + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode("Internal Key Storage Token") +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -211,19 +218,24 @@ public class ConfigureTKS {
// HSM
else {
// login to hsm first
- query_string = "p=2" + "&op=next" + "&xml=true" + "&uTokName="
- + URLEncoder.encode(token_name) + "&__uPasswd="
- + URLEncoder.encode(token_pwd) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=2" + "&op=next" + "&xml=true" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
// choice with token name now
- query_string = "p=1" + "&op=next" + "&xml=true" + "&choice="
- + URLEncoder.encode(token_name) + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=1" + "&op=next" + "&xml=true" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -233,18 +245,24 @@ public class ConfigureTKS {
return true;
}
- public boolean DomainPanel() {
+ public boolean DomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
- String query_string = "sdomainURL=" + URLEncoder.encode(domain_url)
- + "&choice=existingdomain" + "&p=3" + "&op=next" + "&xml=true";
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&choice=existingdomain"+
+ "&p=3" +
+ "&op=next" +
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -255,15 +273,16 @@ public class ConfigureTKS {
}
- public boolean DisplayChainPanel() {
+ public boolean DisplayChainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String query_string = null;
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -273,41 +292,46 @@ public class ConfigureTKS {
}
- public boolean SecurityDomainLoginPanel() {
+ public boolean SecurityDomainLoginPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String tks_url = "https://" + cs_hostname + ":" + cs_port
- + "/tks/admin/console/config/wizard" + "?p=5&subsystem=TKS";
- String query_string = "url=" + URLEncoder.encode(tks_url);
+ String tks_url = "https://" + cs_hostname + ":" + cs_port +
+ "/tks/admin/console/config/wizard" +
+ "?p=5&subsystem=TKS" ;
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
+ String query_string = "url=" + URLEncoder.encode(tks_url);
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(tks_url);
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(tks_url) ;
+
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
// get session id from security domain
String tks_session_id = hr.getContentValue("header.session_id");
String tks_url_1 = hr.getContentValue("header.url");
- System.out.println("TKS_SESSION_ID=" + tks_session_id);
- System.out.println("TKS_URL=" + tks_url_1);
+ System.out.println("TKS_SESSION_ID=" + tks_session_id );
+ System.out.println("TKS_URL=" + tks_url_1 );
// use session id to connect back to TKS
- String query_string_2 = "p=5" + "&subsystem=TKS" + "&session_id="
- + tks_session_id + "&xml=true";
+ String query_string_2 = "p=5" +
+ "&subsystem=TKS" +
+ "&session_id=" + tks_session_id +
+ "&xml=true" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -317,18 +341,20 @@ public class ConfigureTKS {
return true;
}
-
- public boolean SubsystemPanel() {
+
+ public boolean SubsystemPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=5" + "&op=next" + "&xml=true"
- + "&subsystemName=" + URLEncoder.encode(subsystem_name)
- + "&choice=newsubsystem";
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&choice=newsubsystem" ;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
@@ -337,25 +363,27 @@ public class ConfigureTKS {
return true;
}
- public boolean LdapConnectionPanel() {
+ public boolean LdapConnectionPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=7" + "&op=next" + "&xml=true" + "&host="
- + URLEncoder.encode(ldap_host) + "&port="
- + URLEncoder.encode(ldap_port) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&display="
- + URLEncoder.encode("$displayStr")
- + (secure_conn.equals("true") ? "&secureConn=on" : "")
- + (clone_start_tls.equals("true") ? "&cloneStartTLS=on" : "")
- + (remove_data.equals("true") ? "&removeData=true" : "");
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=7" + "&op=next" + "&xml=true" +
+ "&host=" + URLEncoder.encode(ldap_host) +
+ "&port=" + URLEncoder.encode(ldap_port) +
+ "&binddn=" + URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" + URLEncoder.encode(bind_password) +
+ "&basedn=" + URLEncoder.encode(base_dn) +
+ "&database=" + URLEncoder.encode(db_name) +
+ "&display=" + URLEncoder.encode("$displayStr") +
+ (secure_conn.equals("true")? "&secureConn=on": "") +
+ (clone_start_tls.equals("true")? "&cloneStartTLS=on": "") +
+ (remove_data.equals("true")? "&removeData=true": "");
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -365,56 +393,46 @@ public class ConfigureTKS {
return true;
}
- public boolean KeyPanel() {
+ public boolean KeyPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
ArrayList<String> al = null;
- String query_string = "p=8" + "&op=next" + "&xml=true"
- + "&subsystem_custom_size="
- + subsystem_key_size
- + "&sslserver_custom_size="
- + sslserver_key_size
- + "&audit_signing_custom_size="
- + audit_signing_key_size
- + "&custom_size="
- + key_size
- + "&subsystem_custom_curvename="
- + subsystem_key_curvename
- + "&sslserver_custom_curvename="
- + sslserver_key_curvename
- + "&audit_signing_custom_curvename="
- + audit_signing_key_curvename
- + "&custom_curvename="
- + key_curvename
- + "&subsystem_keytype="
- + subsystem_key_type
- + "&sslserver_keytype="
- + sslserver_key_type
- + "&audit_signing_keytype="
- + audit_signing_key_type
- + "&keytype="
- + key_type
- + "&subsystem_choice=custom"
- + "&sslserver_choice=custom"
- + "&audit_signing_choice=custom"
- + "&choice=custom";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+
+ String query_string = "p=8" + "&op=next" + "&xml=true" +
+ "&subsystem_custom_size=" + subsystem_key_size +
+ "&sslserver_custom_size=" + sslserver_key_size +
+ "&audit_signing_custom_size=" + audit_signing_key_size +
+ "&custom_size=" + key_size +
+ "&subsystem_custom_curvename=" + subsystem_key_curvename +
+ "&sslserver_custom_curvename=" + sslserver_key_curvename +
+ "&audit_signing_custom_curvename=" + audit_signing_key_curvename +
+ "&custom_curvename=" + key_curvename +
+ "&subsystem_keytype=" + subsystem_key_type +
+ "&sslserver_keytype=" + sslserver_key_type +
+ "&audit_signing_keytype=" + audit_signing_key_type +
+ "&keytype=" + key_type +
+ "&subsystem_choice=custom"+
+ "&sslserver_choice=custom"+
+ "&audit_signing_choice=custom" +
+ "&choice=custom";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- al = px.constructValueList("CertReqPair", "DN");
+
+ al = px.constructValueList("CertReqPair","DN");
// get ca cert subject name
if (al != null) {
- for (int i = 0; i < al.size(); i++) {
- String temp = al.get(i);
- if (temp.indexOf("TKS Subsystem") > 0) {
+ for (int i=0; i < al.size(); i++) {
+ String temp = al.get(i);
+ if (temp.indexOf("TKS Subsystem") > 0 ) {
tks_subsystem_cert_name = temp;
} else if (temp.indexOf("Audit Signing Certificate") > 0) {
tks_audit_signing_cert_name = temp;
@@ -423,16 +441,17 @@ public class ConfigureTKS {
}
}
}
-
- System.out.println("default: tks_subsystem_cert_name="
- + tks_subsystem_cert_name);
- System.out.println("default: server_cert_name=" + server_cert_name);
- System.out.println("default: tks_audit_signing_cert_name="
- + tks_audit_signing_cert_name);
+
+ System.out.println("default: tks_subsystem_cert_name=" +
+ tks_subsystem_cert_name);
+ System.out.println("default: server_cert_name=" +
+ server_cert_name);
+ System.out.println("default: tks_audit_signing_cert_name=" + tks_audit_signing_cert_name);
return true;
}
- public boolean CertSubjectPanel() {
+ public boolean CertSubjectPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -441,48 +460,52 @@ public class ConfigureTKS {
ArrayList<String> cert_list = null;
ArrayList<String> dn_list = null;
- String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port;
+ String domain_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
- String query_string = "p=9" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(tks_subsystem_cert_subject_name)
- + "&sslserver="
- + URLEncoder.encode(tks_server_cert_subject_name)
- + "&audit_signing="
- + URLEncoder.encode(tks_audit_signing_cert_subject_name)
- + "&urls=" + URLEncoder.encode(domain_url) + "";
+ String query_string = "p=9" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(tks_subsystem_cert_subject_name) +
+ "&sslserver=" +
+ URLEncoder.encode(tks_server_cert_subject_name) +
+ "&audit_signing=" +
+ URLEncoder.encode(tks_audit_signing_cert_subject_name) +
+ "&urls=" +
+ URLEncoder.encode(domain_url) +
+ "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- req_list = px.constructValueList("CertReqPair", "Request");
- cert_list = px.constructValueList("CertReqPair", "Certificate");
- dn_list = px.constructValueList("CertReqPair", "Nickname");
+
+ req_list = px.constructValueList("CertReqPair","Request");
+ cert_list = px.constructValueList("CertReqPair","Certificate");
+ dn_list = px.constructValueList("CertReqPair","Nickname");
if (req_list != null && cert_list != null && dn_list != null) {
- for (int i = 0; i < dn_list.size(); i++) {
- String temp = dn_list.get(i);
-
- if (temp.indexOf("subsystemCert") >= 0) {
- tks_subsystem_cert_req = req_list.get(i);
- tks_subsystem_cert_cert = cert_list.get(i);
- } else if (temp.indexOf("auditSigningCert") >= 0) {
- tks_audit_signing_cert_req = req_list.get(i);
- tks_audit_signing_cert_cert = cert_list.get(i);
+ for (int i=0; i < dn_list.size(); i++) {
+ String temp = dn_list.get(i);
+
+ if (temp.indexOf("subsystemCert") >= 0 ) {
+ tks_subsystem_cert_req = req_list.get(i);
+ tks_subsystem_cert_cert = cert_list.get(i);
+ } else if (temp.indexOf("auditSigningCert") >=0) {
+ tks_audit_signing_cert_req = req_list.get(i);
+ tks_audit_signing_cert_cert = cert_list.get(i);
} else {
- server_cert_req = req_list.get(i);
- server_cert_cert = cert_list.get(i);
+ server_cert_req = req_list.get(i);
+ server_cert_cert = cert_list.get(i);
}
}
}
-
+
return true;
}
- public boolean CertificatePanel() {
+ public boolean CertificatePanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -492,75 +515,85 @@ public class ConfigureTKS {
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
- String query_string = "p=10" + "&op=next" + "&xml=true" + "&subsystem="
- + URLEncoder.encode(tks_subsystem_cert_cert) + "&subsystem_cc="
- + "&sslserver=" + URLEncoder.encode(server_cert_cert)
- + "&sslserver_cc=" + "&audit_signing="
- + URLEncoder.encode(tks_audit_signing_cert_cert)
- + "&audit_signing_cc=" + "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=10" + "&op=next" + "&xml=true" +
+ "&subsystem=" +
+ URLEncoder.encode(tks_subsystem_cert_cert) +
+ "&subsystem_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&audit_signing=" +
+ URLEncoder.encode(tks_audit_signing_cert_cert) +
+ "&audit_signing_cc=" +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
-
+
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean BackupPanel() {
+ public boolean BackupPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=11" + "&op=next" + "&xml=true"
- + "&choice=backupkey" + "&__pwd="
- + URLEncoder.encode(backup_pwd) + "&__pwdagain="
- + URLEncoder.encode(backup_pwd);
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=11" + "&op=next" + "&xml=true" +
+ "&choice=backupkey" +
+ "&__pwd=" + URLEncoder.encode(backup_pwd) +
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean SavePKCS12Panel() {
+ public boolean SavePKCS12Panel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "";
- hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
+ String query_string = "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,pkcs12_uri,query_string);
// dump hr.getResponseData() to file
- try {
+ try
+ {
FileOutputStream fos = new FileOutputStream(backup_fname);
fos.write(hr.getResponseData());
fos.close();
// set file to permissions 600
- String rtParams[] = { "chmod", "600", backup_fname };
+ String rtParams[] = { "chmod","600", backup_fname};
Process proc = Runtime.getRuntime().exec(rtParams);
- BufferedReader br = new BufferedReader(new InputStreamReader(
- proc.getErrorStream()));
+ BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
- while ((line = br.readLine()) != null)
- System.out.println("Error: " + line);
+ while ( (line = br.readLine()) != null)
+ System.out.println("Error: " + line);
int exitVal = proc.waitFor();
-
+
// verify p12 file
-
+
// Decode the P12 file
FileInputStream fis = new FileInputStream(backup_fname);
PFX.Template pfxt = new PFX.Template();
@@ -568,14 +601,14 @@ public class ConfigureTKS {
System.out.println("Decoded PFX");
// now peruse it for interesting info
- System.out.println("Version: " + pfx.getVersion());
+ System.out.println("Version: "+pfx.getVersion());
AuthenticatedSafes authSafes = pfx.getAuthSafes();
SEQUENCE asSeq = authSafes.getSequence();
- System.out.println("AuthSafes has " + asSeq.size()
- + " SafeContents");
+ System.out.println("AuthSafes has "+
+ asSeq.size()+" SafeContents");
fis.close();
- } catch (Exception e) {
+ } catch(Exception e) {
System.out.println("ERROR: Exception=" + e.getMessage());
return false;
}
@@ -583,17 +616,22 @@ public class ConfigureTKS {
return true;
}
- public boolean AdminCertReqPanel() {
+ public boolean AdminCertReqPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
String admin_cert_request = null;
+
String cert_subject = "CN=tks-" + admin_user;
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.setTransportCert(null);
@@ -602,68 +640,80 @@ public class ConfigureTKS {
String crmf_request = cCrypt.generateCRMFrequest();
- if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
+ if (crmf_request == null)
+ {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
return false;
}
admin_cert_request = crmf_request;
- String query_string = "p=13" + "&op=next" + "&xml=true"
- + "&cert_request_type=" + "crmf" + "&uid=" + admin_user
- + "&name=" + admin_user + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&profileId="
- + "caAdminCert" + "&email=" + URLEncoder.encode(admin_email)
- + "&cert_request=" + URLEncoder.encode(admin_cert_request)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&clone=new" + "&import=true" + "&securitydomain="
- + URLEncoder.encode(domain_name) + "";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ String query_string = "p=13" + "&op=next" + "&xml=true" +
+ "&cert_request_type=" + "crmf" +
+ "&uid=" + admin_user +
+ "&name=" + admin_user +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&profileId=" + "caAdminCert" +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&clone=new" +
+ "&import=true" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
+
+ admin_serial_number = px.getvalue("serialNumber");
return true;
}
- public boolean AdminCertImportPanel() {
+ public boolean AdminCertImportPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true" + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "";
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
+
// get response data
- // String cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- String cert_to_import = OSUtil.BtoA(hr.getResponseData());
+ // String cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ String cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -671,30 +721,37 @@ public class ConfigureTKS {
return true;
}
- public boolean UpdateDomainPanel() {
+ public boolean UpdateDomainPanel()
+ {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
- String query_string = "p=14" + "&op=next" + "&xml=true" + "&caHost="
- + URLEncoder.encode(sd_hostname) + "&caPort="
- + URLEncoder.encode(sd_agent_port) + "";
+ String query_string = "p=14" + "&op=next" + "&xml=true" +
+ "&caHost=" + URLEncoder.encode(sd_hostname) +
+ "&caPort=" + URLEncoder.encode(sd_agent_port) +
+ "";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
px.parse(bais);
px.prettyprintxml();
-
+
return true;
}
- public boolean ConfigureTKSInstance() {
+
+ public boolean ConfigureTKSInstance()
+ {
// 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
cCrypt.loginDB();
@@ -714,8 +771,7 @@ public class ConfigureTKS {
// 2. Token Choice Panel
boolean disp_token = TokenChoicePanel();
if (!disp_token) {
- System.out
- .println("ERROR: ConfigureTKS: TokenChoicePanel() failure");
+ System.out.println("ERROR: ConfigureTKS: TokenChoicePanel() failure");
return false;
}
@@ -731,8 +787,7 @@ public class ConfigureTKS {
// 4. display cert chain panel
boolean disp_st = DisplayChainPanel();
if (!disp_st) {
- System.out
- .println("ERROR: ConfigureTKS: DisplayChainPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: DisplayChainPanel() failure");
return false;
}
@@ -740,8 +795,7 @@ public class ConfigureTKS {
// security domain login panel
boolean disp_sd = SecurityDomainLoginPanel();
if (!disp_sd) {
- System.out
- .println("ERROR: ConfigureTKS: SecurityDomainLoginPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: SecurityDomainLoginPanel() failure");
return false;
}
@@ -752,13 +806,12 @@ public class ConfigureTKS {
System.out.println("ERROR: ConfigureTKS: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureTKS: LdapConnectionPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: LdapConnectionPanel() failure");
return false;
}
@@ -775,8 +828,7 @@ public class ConfigureTKS {
// 10. Cert Subject Panel
boolean disp_csubj = CertSubjectPanel();
if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureTKS: CertSubjectPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: CertSubjectPanel() failure");
return false;
}
@@ -784,8 +836,7 @@ public class ConfigureTKS {
// 11. Certificate Panel
boolean disp_cp = CertificatePanel();
if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureTKS: CertificatePanel() failure");
+ System.out.println("ERROR: ConfigureTKS: CertificatePanel() failure");
return false;
}
@@ -801,8 +852,7 @@ public class ConfigureTKS {
// save panel
boolean disp_save = SavePKCS12Panel();
if (!disp_save) {
- System.out
- .println("ERROR: ConfigureTKS: SavePKCS12Panel() failure");
+ System.out.println("ERROR: ConfigureTKS: SavePKCS12Panel() failure");
return false;
}
@@ -810,8 +860,7 @@ public class ConfigureTKS {
// 13. Admin Cert Req Panel
boolean disp_adm = AdminCertReqPanel();
if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureTKS: AdminCertReqPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: AdminCertReqPanel() failure");
return false;
}
@@ -819,8 +868,7 @@ public class ConfigureTKS {
// 14. Admin Cert import Panel
boolean disp_im = AdminCertImportPanel();
if (!disp_im) {
- System.out
- .println("ERROR: ConfigureTKS: AdminCertImportPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: AdminCertImportPanel() failure");
return false;
}
@@ -828,8 +876,7 @@ public class ConfigureTKS {
// 15. Update Domain Panel
boolean disp_ud = UpdateDomainPanel();
if (!disp_ud) {
- System.out
- .println("ERROR: ConfigureTKS: UpdateDomainPanel() failure");
+ System.out.println("ERROR: ConfigureTKS: UpdateDomainPanel() failure");
return false;
}
@@ -845,7 +892,8 @@ public class ConfigureTKS {
}
}
- public static void main(String args[]) {
+ public static void main(String args[])
+ {
ConfigureTKS ca = new ConfigureTKS();
// set variables
@@ -873,7 +921,7 @@ public class ConfigureTKS {
StringHolder x_admin_email = new StringHolder();
StringHolder x_admin_password = new StringHolder();
- // ldap
+ // ldap
StringHolder x_ldap_host = new StringHolder();
StringHolder x_ldap_port = new StringHolder();
StringHolder x_bind_dn = new StringHolder();
@@ -926,140 +974,122 @@ public class ConfigureTKS {
// parse the args
ArgParser parser = new ArgParser("ConfigureTKS");
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL Admin port", x_cs_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain Admin Name",
- x_sd_admin_name);
- parser.addOption(
- "-sd_admin_password %s #Security Domain Admin password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL EE port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL EE port", x_ca_ssl_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
- parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
- parser.addOption(
- "-secure_conn %s #use ldaps port (optional, default is false)",
- x_secure_conn);
- parser.addOption(
- "-remove_data %s #remove existing data under base_dn (optional, default is false) ",
- x_remove_data);
- parser.addOption(
- "-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)",
- x_clone_start_tls);
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL Admin port",
+ x_cs_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain Admin Name",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain Admin password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL EE port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL EE port",
+ x_ca_ssl_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption ("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption ("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption ("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption ("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption ("-db_name %s #db name",
+ x_db_name);
+ parser.addOption("-secure_conn %s #use ldaps port (optional, default is false)", x_secure_conn);
+ parser.addOption("-remove_data %s #remove existing data under base_dn (optional, default is false) ", x_remove_data);
+ parser.addOption("-clone_start_tls %s #use startTLS for cloning replication agreement (optional, default is false)", x_clone_start_tls);
// key and algorithm options (default)
- parser.addOption(
- "-key_type %s #Key type [RSA,ECC] (optional, default is RSA)",
- x_key_type);
- parser.addOption(
- "-key_size %s #Key Size (optional, for RSA default is 2048)",
- x_key_size);
- parser.addOption(
- "-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)",
- x_key_curvename);
-
- // key and algorithm options for audit_signing certificate (overrides
- // default)
- parser.addOption(
- "-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_audit_signing_key_type);
- parser.addOption(
- "-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_audit_signing_key_size);
- parser.addOption(
- "-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_audit_signing_key_curvename);
-
- // key and algorithm options for subsystem certificate (overrides
- // default)
- parser.addOption(
- "-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_subsystem_key_type);
- parser.addOption(
- "-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_subsystem_key_size);
- parser.addOption(
- "-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_subsystem_key_curvename);
-
- // key and algorithm options for sslserver certificate (overrides
- // default)
- parser.addOption(
- "-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)",
- x_sslserver_key_type);
- parser.addOption(
- "-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)",
- x_sslserver_key_size);
- parser.addOption(
- "-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)",
- x_sslserver_key_curvename);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
-
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent Cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent Cert Subject",
- x_agent_cert_subject);
-
- parser.addOption("-backup_pwd %s #PKCS12 password", x_backup_pwd);
-
- parser.addOption(
- "-tks_subsystem_cert_subject_name %s #TKS subsystem cert subject name",
- x_tks_subsystem_cert_subject_name);
- parser.addOption(
- "-tks_server_cert_subject_name %s #TKS server cert subject name",
- x_tks_server_cert_subject_name);
+ parser.addOption("-key_type %s #Key type [RSA,ECC] (optional, default is RSA)", x_key_type);
+ parser.addOption("-key_size %s #Key Size (optional, for RSA default is 2048)", x_key_size);
+ parser.addOption("-key_curvename %s #Key Curve Name (optional, for ECC default is nistp256)", x_key_curvename);
+
+ // key and algorithm options for audit_signing certificate (overrides default)
+ parser.addOption("-audit_signing_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_audit_signing_key_type);
+ parser.addOption("-audit_signing_key_size %s #Key Size (optional, for RSA default is key_size)", x_audit_signing_key_size);
+ parser.addOption("-audit_signing_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_audit_signing_key_curvename);
+
+ // key and algorithm options for subsystem certificate (overrides default)
+ parser.addOption("-subsystem_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_subsystem_key_type);
+ parser.addOption("-subsystem_key_size %s #Key Size (optional, for RSA default is key_size)", x_subsystem_key_size);
+ parser.addOption("-subsystem_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_subsystem_key_curvename);
+
+ // key and algorithm options for sslserver certificate (overrides default)
+ parser.addOption("-sslserver_key_type %s #Key type [RSA,ECC] (optional, default is key_type)", x_sslserver_key_type);
+ parser.addOption("-sslserver_key_size %s #Key Size (optional, for RSA default is key_size)", x_sslserver_key_size);
+ parser.addOption("-sslserver_key_curvename %s #Key Curve Name (optional, for ECC default is key_curvename)", x_sslserver_key_curvename);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent Cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent Cert Subject",
+ x_agent_cert_subject);
+
+ parser.addOption ("-backup_pwd %s #PKCS12 password",
+ x_backup_pwd);
+
+ parser.addOption (
+ "-tks_subsystem_cert_subject_name %s #TKS subsystem cert subject name",
+ x_tks_subsystem_cert_subject_name);
+ parser.addOption (
+ "-tks_server_cert_subject_name %s #TKS server cert subject name",
+ x_tks_server_cert_subject_name);
+
+ parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-tks.p12",
+ x_backup_fname);
+
+ parser.addOption (
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
parser.addOption(
- "-backup_fname %s #Backup File for p12, (optional, default /root/tmp-tks.p12",
- x_backup_fname);
-
- parser.addOption("-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
- parser.addOption(
- "-tks_audit_signing_cert_subject_name %s #TKS audit signing cert subject name",
- x_tks_audit_signing_cert_subject_name);
+ "-tks_audit_signing_cert_subject_name %s #TKS audit signing cert subject name",
+ x_tks_audit_signing_cert_subject_name);
// and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
- if (unmatched != null) {
+ if (unmatched!=null) {
System.out.println("ERROR: Argument Mismatch");
System.exit(-1);
}
@@ -1102,25 +1132,19 @@ public class ConfigureTKS {
clone_start_tls = set_default(x_clone_start_tls.value, "false");
key_type = set_default(x_key_type.value, DEFAULT_KEY_TYPE);
- audit_signing_key_type = set_default(x_audit_signing_key_type.value,
- key_type);
+ audit_signing_key_type = set_default(x_audit_signing_key_type.value, key_type);
subsystem_key_type = set_default(x_subsystem_key_type.value, key_type);
sslserver_key_type = set_default(x_sslserver_key_type.value, key_type);
key_size = set_default(x_key_size.value, DEFAULT_KEY_SIZE);
- audit_signing_key_size = set_default(x_audit_signing_key_size.value,
- key_size);
+ audit_signing_key_size = set_default(x_audit_signing_key_size.value, key_size);
subsystem_key_size = set_default(x_subsystem_key_size.value, key_size);
sslserver_key_size = set_default(x_sslserver_key_size.value, key_size);
- key_curvename = set_default(x_key_curvename.value,
- DEFAULT_KEY_CURVENAME);
- audit_signing_key_curvename = set_default(
- x_audit_signing_key_curvename.value, key_curvename);
- subsystem_key_curvename = set_default(x_subsystem_key_curvename.value,
- key_curvename);
- sslserver_key_curvename = set_default(x_sslserver_key_curvename.value,
- key_curvename);
+ key_curvename = set_default(x_key_curvename.value, DEFAULT_KEY_CURVENAME);
+ audit_signing_key_curvename = set_default(x_audit_signing_key_curvename.value, key_curvename);
+ subsystem_key_curvename = set_default(x_subsystem_key_curvename.value, key_curvename);
+ sslserver_key_curvename = set_default(x_sslserver_key_curvename.value, key_curvename);
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
@@ -1131,23 +1155,25 @@ public class ConfigureTKS {
backup_pwd = x_backup_pwd.value;
backup_fname = set_default(x_backup_fname.value, "/root/tmp-tks.p12");
-
- tks_subsystem_cert_subject_name = x_tks_subsystem_cert_subject_name.value;
- tks_server_cert_subject_name = x_tks_server_cert_subject_name.value;
-
- subsystem_name = x_subsystem_name.value;
+
+ tks_subsystem_cert_subject_name =
+ x_tks_subsystem_cert_subject_name.value;
+ tks_server_cert_subject_name =
+ x_tks_server_cert_subject_name.value ;
+
+ subsystem_name = x_subsystem_name.value ;
tks_audit_signing_cert_subject_name = x_tks_audit_signing_cert_subject_name.value;
boolean st = ca.ConfigureTKSInstance();
-
+
if (!st) {
System.out.println("ERROR: unable to create TKS");
System.exit(-1);
}
-
+
System.out.println("Certificate System - TKS Instance Configured.");
System.exit(0);
-
+
}
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
index 30b33bfc..5273fda7 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -30,994 +29,1155 @@ import com.netscape.pkisilent.common.ParseXML;
import com.netscape.pkisilent.http.HTTPClient;
import com.netscape.pkisilent.http.HTTPResponse;
-public class ConfigureTPS {
- // define global variables
-
- public static HTTPClient hc = null;
-
- public static String login_uri = "/tps/admin/console/config/login";
- public static String wizard_uri = "/tps/admin/console/config/wizard";
- public static String admin_uri = "/ca/admin/ca/getBySerial";
-
- public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
- public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
- public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
- public static String pkcs12_uri = "/tps/admin/console/config/savepkcs12";
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String cs_clientauth_port = null;
-
- public static String sd_hostname = null;
- public static String sd_ssl_port = null;
- public static String sd_agent_port = null;
- public static String sd_admin_port = null;
- public static String sd_admin_name = null;
- public static String sd_admin_password = null;
-
- public static String ca_hostname = null;
- public static String ca_port = null;
- public static String ca_ssl_port = null;
- public static String ca_admin_port = null;
-
- public static String drm_hostname = null;
- public static String drm_ssl_port = null;
-
- public static String tks_hostname = null;
- public static String tks_ssl_port = null;
-
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
-
- // Login Panel
- public static String pin = null;
-
- public static String domain_name = null;
-
- public static String admin_user = null;
- public static String admin_email = null;
- public static String admin_password = null;
- public static String admin_serial_number = null;
- public static String agent_name = null;
-
- public static String ldap_auth_host = null;
- public static String ldap_auth_port = null;
- public static String ldap_auth_base_dn = null;
-
- public static String ldap_host = null;
- public static String ldap_port = null;
- public static String bind_dn = null;
- public static String bind_password = null;
- public static String base_dn = null;
- public static String db_name = null;
-
- public static String key_size = null;
- public static String key_type = null;
- public static String token_name = null;
- public static String token_pwd = null;
-
- public static String agent_key_size = null;
- public static String agent_key_type = null;
- public static String agent_cert_subject = null;
-
- public static String tps_transport_cert_name = null;
- public static String tps_transport_cert_req = null;
- public static String tps_transport_cert_pp = null;
- public static String tps_transport_cert_cert = null;
-
- public static String tps_storage_cert_name = null;
- public static String tps_storage_cert_req = null;
- public static String tps_storage_cert_pp = null;
- public static String tps_storage_cert_cert = null;
-
- public static String server_cert_name = null;
- public static String server_cert_req = null;
- public static String server_cert_pp = null;
- public static String server_cert_cert = null;
-
- public static String tps_subsystem_cert_name = null;
- public static String tps_subsystem_cert_req = null;
- public static String tps_subsystem_cert_pp = null;
- public static String tps_subsystem_cert_cert = null;
-
- public static String tps_audit_signing_cert_name = null;
- public static String tps_audit_signing_cert_req = null;
- public static String tps_audit_signing_cert_pp = null;
- public static String tps_audit_signing_cert_cert = null;
-
- public static String ss_keygen = null;
-
- // names
- public static String tps_server_cert_subject_name = null;
- public static String tps_server_cert_nickname = null;
- public static String tps_subsystem_cert_subject_name = null;
- public static String tps_subsystem_cert_nickname = null;
- public static String tps_audit_signing_cert_subject_name = null;
- public static String tps_audit_signing_cert_nickname = null;
- public static String subsystem_name = null;
-
- // Security Domain Login Panel
- public static String tps_session_id = null;
-
- // Admin Certificate Request Panel
- public static String requestor_name = null;
-
- public ConfigureTPS() {
- // do nothing :)
- }
-
- public void sleep_time() {
- try {
- System.out.println("Sleeping for 5 secs..");
- Thread.sleep(5000);
- } catch (Exception e) {
- System.out.println("ERROR: sleep problem");
- }
-
- }
-
- public boolean LoginPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "pin=" + pin + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, login_uri, query_string);
- System.out.println("xml returned: " + hr.getHTML());
-
- // parse xml here - nothing to parse
-
- // no cookie for tps
- // get cookie
- String temp = hr.getCookieValue("pin");
-
- if (temp != null) {
- int index = temp.indexOf(";");
- HTTPClient.j_session_id = temp.substring(0, index);
- st = true;
- }
-
- hr = null;
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
- "p=0&op=next&xml=true");
-
- // parse xml here
-
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- st = true;
- return st;
- }
-
- public boolean DomainPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
-
- String query_string = "p=3" + "&choice=existingdomain" + "&sdomainURL="
- + URLEncoder.encode(domain_url) + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
-
- }
-
- public boolean DisplayChainPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String query_string = null;
-
- query_string = "p=4" + "&op=next" + "&xml=true";
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- return true;
-
- }
-
- public boolean SecurityDomainLoginPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String tps_url = "https://" + cs_hostname + ":" + cs_port
- + "/tps/admin/console/config/wizard" + "?p=3&subsystem=TPS";
-
- String query_string = "url=" + URLEncoder.encode(tps_url) + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_login_uri,
- query_string);
-
- String query_string_1 = "uid=" + sd_admin_name + "&pwd="
- + URLEncoder.encode(sd_admin_password) + "&url="
- + URLEncoder.encode(tps_url) + "";
-
- hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
- query_string_1);
-
- // get session id from security domain
- sleep_time();
-
- tps_session_id = hr.getContentValue("header.session_id");
- String tps_url_1 = hr.getContentValue("header.url");
-
- System.out.println("TPS_SESSION_ID=" + tps_session_id);
- System.out.println("TPS_URL=" + tps_url_1);
-
- // use session id to connect back to TPS
-
- String query_string_2 = "p=5" + "&subsystem=TPS" + "&session_id="
- + tps_session_id + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_2);
-
- // parse xml - no parsing
-
- return true;
-
- }
-
- public boolean SubsystemPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- sleep_time();
- String query_string = "p=5" + "&choice=newsubsystem"
- + "&subsystemName=" + URLEncoder.encode(subsystem_name)
- + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- sleep_time();
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
-
- // CA choice panel
- query_string = "p=6" + "&urls=0" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+public class ConfigureTPS
+{
+ // define global variables
+
+ public static HTTPClient hc = null;
+
+ public static String login_uri = "/tps/admin/console/config/login";
+ public static String wizard_uri = "/tps/admin/console/config/wizard";
+ public static String admin_uri = "/ca/admin/ca/getBySerial";
+
+ public static String sd_login_uri = "/ca/admin/ca/securityDomainLogin";
+ public static String sd_get_cookie_uri = "/ca/admin/ca/getCookie";
+ public static String sd_update_domain_uri = "/ca/agent/ca/updateDomainXML";
+ public static String pkcs12_uri = "/tps/admin/console/config/savepkcs12";
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String cs_clientauth_port = null;
+
+ public static String sd_hostname = null;
+ public static String sd_ssl_port = null;
+ public static String sd_agent_port = null;
+ public static String sd_admin_port = null;
+ public static String sd_admin_name = null;
+ public static String sd_admin_password = null;
+
+ public static String ca_hostname = null;
+ public static String ca_port = null;
+ public static String ca_ssl_port = null;
+ public static String ca_admin_port = null;
+
+ public static String drm_hostname = null;
+ public static String drm_ssl_port = null;
+
+ public static String tks_hostname = null;
+ public static String tks_ssl_port = null;
+
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+
+ // Login Panel
+ public static String pin = null;
+
+ public static String domain_name = null;
+
+ public static String admin_user = null;
+ public static String admin_email = null;
+ public static String admin_password = null;
+ public static String admin_serial_number = null;
+ public static String agent_name = null;
+
+ public static String ldap_auth_host = null;
+ public static String ldap_auth_port = null;
+ public static String ldap_auth_base_dn = null;
+
+ public static String ldap_host = null;
+ public static String ldap_port = null;
+ public static String bind_dn = null;
+ public static String bind_password = null;
+ public static String base_dn = null;
+ public static String db_name = null;
+
+ public static String key_size = null;
+ public static String key_type = null;
+ public static String token_name = null;
+ public static String token_pwd = null;
+
+ public static String agent_key_size = null;
+ public static String agent_key_type = null;
+ public static String agent_cert_subject = null;
+
+ public static String tps_transport_cert_name = null;
+ public static String tps_transport_cert_req = null;
+ public static String tps_transport_cert_pp = null;
+ public static String tps_transport_cert_cert = null;
+
+ public static String tps_storage_cert_name = null;
+ public static String tps_storage_cert_req = null;
+ public static String tps_storage_cert_pp = null;
+ public static String tps_storage_cert_cert = null;
+
+ public static String server_cert_name = null;
+ public static String server_cert_req = null;
+ public static String server_cert_pp = null;
+ public static String server_cert_cert = null;
+
+ public static String tps_subsystem_cert_name = null;
+ public static String tps_subsystem_cert_req = null;
+ public static String tps_subsystem_cert_pp = null;
+ public static String tps_subsystem_cert_cert = null;
+
+ public static String tps_audit_signing_cert_name = null;
+ public static String tps_audit_signing_cert_req = null;
+ public static String tps_audit_signing_cert_pp = null;
+ public static String tps_audit_signing_cert_cert = null;
+
+ public static String ss_keygen = null;
+
+ // names
+ public static String tps_server_cert_subject_name = null;
+ public static String tps_server_cert_nickname = null;
+ public static String tps_subsystem_cert_subject_name = null;
+ public static String tps_subsystem_cert_nickname = null;
+ public static String tps_audit_signing_cert_subject_name = null;
+ public static String tps_audit_signing_cert_nickname = null;
+ public static String subsystem_name = null;
+
+ // Security Domain Login Panel
+ public static String tps_session_id = null;
+
+ // Admin Certificate Request Panel
+ public static String requestor_name = null;
+
+ public ConfigureTPS ()
+ {
+ // do nothing :)
+ }
+
+ public void sleep_time()
+ {
+ try
+ {
+ System.out.println("Sleeping for 5 secs..");
+ Thread.sleep(5000);
+ }
+ catch(Exception e)
+ {
+ System.out.println("ERROR: sleep problem");
+ }
+
+ }
+
+ public boolean LoginPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ String query_string = "pin=" + pin + "&xml=true";
+
+ hr = hc.sslConnect(cs_hostname,cs_port,login_uri,query_string);
+ System.out.println("xml returned: " + hr.getHTML());
+
+ // parse xml here - nothing to parse
+
+ // no cookie for tps
+ // get cookie
+ String temp = hr.getCookieValue("pin");
+
+ if(temp!=null)
+ {
+ int index = temp.indexOf(";");
+ HTTPClient.j_session_id = temp.substring(0,index);
+ st = true;
+ }
+
+ hr = null;
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ "p=0&op=next&xml=true");
- sleep_time();
- // TKS choice panel
- String tks_url = "https://" + tks_hostname + ":" + tks_ssl_port;
- query_string = "p=7" + "&urls=0" + "&op=next" + "&xml=true";
+ // parse xml here
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // DRM / server side keygen panel
-
- sleep_time();
- if (ss_keygen.equalsIgnoreCase("true")) {
- ss_keygen = "keygen";
- }
-
- String drm_url = "https://" + drm_hostname + ":" + drm_ssl_port;
-
- query_string = "p=8" + "&choice=" + ss_keygen + "&urls=0" + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean LdapAuthConnectionPanel() {
- // auth db
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "p=9" + "&host="
- + URLEncoder.encode(ldap_auth_host) + "&port="
- + URLEncoder.encode(ldap_auth_port) + "&basedn="
- + URLEncoder.encode(ldap_auth_base_dn) + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean LdapConnectionPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- String query_string = "p=10" + "&host=" + URLEncoder.encode(ldap_host)
- + "&port=" + URLEncoder.encode(ldap_port) + "&binddn="
- + URLEncoder.encode(bind_dn) + "&__bindpwd="
- + URLEncoder.encode(bind_password) + "&basedn="
- + URLEncoder.encode(base_dn) + "&database="
- + URLEncoder.encode(db_name) + "&display="
- + URLEncoder.encode("") + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean TokenChoicePanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
-
- // //////////////////////////////////////////////////////
- String query_string = null;
-
- // Software Token
- if (token_name.equalsIgnoreCase("internal")) {
- query_string = "p=1" + "&choice="
- + URLEncoder.encode("NSS Certificate DB") + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
- }
- // HSM
- else {
- // login to hsm first
- query_string = "p=2" + "&uTokName=" + URLEncoder.encode(token_name)
- + "&__uPasswd=" + URLEncoder.encode(token_pwd) + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // choice with token name now
- query_string = "p=1" + "&choice=" + URLEncoder.encode(token_name)
- + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- }
-
- return true;
- }
-
- public boolean KeyPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> friendly_list = null;
- ArrayList<String> dn_list = null;
-
- String query_string = "p=11" + "&keytype=" + key_type
- + "&choice=default" + "&custom_size=" + key_size
- + "&sslserver_keytype=" + key_type + "&sslserver_choice=custom"
- + "&sslserver_custom_size=" + key_size + "&subsystem_keytype="
- + key_type + "&subsystem_choice=custom"
- + "&subsystem_custom_size=" + key_size
- + "&audit_signing_keytype=" + key_type
- + "&audit_signing_choice=default"
- + "&audit_signing_custom_size=" + key_size + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean CertSubjectPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
- ArrayList<String> friendly_list = null;
-
- String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port;
-
- String query_string = "p=12" + "&sslserver="
- + URLEncoder.encode(tps_server_cert_subject_name)
- + "&sslserver_nick="
- + URLEncoder.encode(tps_server_cert_nickname) + "&subsystem="
- + URLEncoder.encode(tps_subsystem_cert_subject_name)
- + "&subsystem_nick="
- + URLEncoder.encode(tps_subsystem_cert_nickname)
- + "&audit_signing="
- + URLEncoder.encode(tps_audit_signing_cert_subject_name)
- + "&audit_signing_nick="
- + URLEncoder.encode(tps_audit_signing_cert_nickname)
- + "&urls=0" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- // parse the certs if needed
-
- return true;
- }
-
- public boolean CertificatePanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- ArrayList<String> req_list = null;
- ArrayList<String> cert_list = null;
- ArrayList<String> dn_list = null;
- ArrayList<String> pp_list = null;
-
- String query_string = "p=13" + "&sslserver=" + "&sslserver_cc="
- + "&subsystem=" + "&subsystem_cc=" + "&audit_signing="
- + "&audit_signing_cc=" + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean AdminCertReqPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String admin_cert_request = null;
-
- requestor_name = "TPS-" + cs_hostname + "-" + cs_clientauth_port;
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.setTransportCert(null);
- cCrypt.setDualKey(false);
- cCrypt.loginDB();
-
- String crmf_request = cCrypt.generateCRMFrequest();
-
- if (crmf_request == null) {
- System.out
- .println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
- }
-
- admin_cert_request = crmf_request;
-
- String query_string = "p=14" + "&uid=" + admin_user + "&name="
- + URLEncoder.encode("TPS Administrator") + "&email="
- + URLEncoder.encode(admin_email) + "&__pwd="
- + URLEncoder.encode(admin_password)
- + "&__admin_password_again="
- + URLEncoder.encode(admin_password) + "&cert_request="
- + URLEncoder.encode(admin_cert_request) + "&display=0"
- + "&profileId=" + "caAdminCert" + "&cert_request_type="
- + "crmf" + "&import=true" + "&uid=" + admin_user + "&clone=0"
- + "&securitydomain=" + URLEncoder.encode(domain_name)
- + "&subject=" + URLEncoder.encode(agent_cert_subject)
- + "&requestor_name=" + URLEncoder.encode(requestor_name)
- + "&sessionID=" + tps_session_id + "&auth_hostname="
- + ca_hostname + "&auth_port=" + ca_ssl_port + "&op=next"
- + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- admin_serial_number = px.getvalue("serialNumber");
-
- return true;
- }
-
- public boolean AdminCertImportPanel() {
- boolean st = false;
- HTTPResponse hr = null;
- ByteArrayInputStream bais = null;
- ParseXML px = new ParseXML();
- String cert_to_import = null;
-
- String query_string = "serialNumber=" + admin_serial_number
- + "&importCert=" + "true" + "";
-
- // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
- // whereas RA and TPS use the CA Admin Port associated with
- // the 'CA choice panel' as invoked from the SubsystemPanel()
- // which MAY or MAY NOT be the same CA as the CA specified
- // by the Security Domain.
- hr = hc.sslConnect(ca_hostname, ca_admin_port, admin_uri, query_string);
-
- try {
- // cert_to_import =
- // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
- cert_to_import = OSUtil.BtoA(hr.getResponseData());
-
- } catch (Exception e) {
- System.out.println("ERROR: failed to retrieve cert");
- }
-
- System.out.println("Imported Cert=" + cert_to_import);
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- String start = "-----BEGIN CERTIFICATE-----\r\n";
- String end = "\r\n-----END CERTIFICATE-----";
-
- st = cCrypt.importCert(start + cert_to_import + end, agent_name);
- if (!st) {
- System.out
- .println("ERROR: AdminCertImportPanel() during cert import");
- return false;
- }
-
- System.out.println("SUCCESS: imported admin user cert");
-
- String query_string_1 = "p=15" + "&serialNumber=" + admin_serial_number
- + "&caHost=" + URLEncoder.encode(ca_hostname) + "&caPort="
- + ca_admin_port + "&op=next" + "&xml=true";
-
- hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string_1);
-
- // parse xml
- bais = new ByteArrayInputStream(hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
-
- return true;
- }
-
- public boolean ConfigureTPSInstance() {
- // 0. login to cert db
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- null, null, null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(true);
- cCrypt.loginDB();
-
- // instantiate http client
- hc = new HTTPClient();
-
- sleep_time();
- // 1. Login panel
- boolean log_st = LoginPanel();
- if (!log_st) {
- System.out.println("ERROR: JSESSIONID not found.");
- System.out.println("ERROR: ConfigureTPS: LoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 2. Token Choice Panel
- boolean disp_token = TokenChoicePanel();
- if (!disp_token) {
- System.out
- .println("ERROR: ConfigureTPS: TokenChoicePanel() failure");
- return false;
- }
-
- sleep_time();
- // 3. domain panel
- boolean dom_st = DomainPanel();
- if (!dom_st) {
- System.out.println("ERROR: ConfigureTPS: DomainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 4. display cert chain panel
- boolean disp_st = DisplayChainPanel();
- if (!disp_st) {
- System.out
- .println("ERROR: ConfigureTPS: DisplayChainPanel() failure");
- return false;
- }
-
- sleep_time();
- // 5. security domain login panel
- boolean disp_sd = SecurityDomainLoginPanel();
- if (!disp_sd) {
- System.out
- .println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure");
- return false;
- }
-
- sleep_time();
- // 6. subsystem panel
- boolean disp_ss = SubsystemPanel();
- if (!disp_ss) {
- System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure");
- return false;
- }
-
- sleep_time();
- // 7. ldap auth connection panel
- boolean disp_ldap_auth = LdapAuthConnectionPanel();
- if (!disp_ldap_auth) {
- System.out
- .println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure");
- return false;
- }
-
- sleep_time();
- // 8. ldap connection panel
- boolean disp_ldap = LdapConnectionPanel();
- if (!disp_ldap) {
- System.out
- .println("ERROR: ConfigureTPS: LdapConnectionPanel() failure");
- return false;
- }
-
- sleep_time();
- // 11. Key Panel
- boolean disp_key = KeyPanel();
- if (!disp_key) {
- System.out.println("ERROR: ConfigureTPS: KeyPanel() failure");
- return false;
- }
-
- sleep_time();
- // 12. Cert Subject Panel
- boolean disp_csubj = CertSubjectPanel();
- if (!disp_csubj) {
- System.out
- .println("ERROR: ConfigureTPS: CertSubjectPanel() failure");
- return false;
- }
-
- sleep_time();
- // 13. Certificate Panel
- boolean disp_cp = CertificatePanel();
- if (!disp_cp) {
- System.out
- .println("ERROR: ConfigureTPS: CertificatePanel() failure");
- return false;
- }
-
- sleep_time();
- // 14. Admin Cert Req Panel
- boolean disp_adm = AdminCertReqPanel();
- if (!disp_adm) {
- System.out
- .println("ERROR: ConfigureTPS: AdminCertReqPanel() failure");
- return false;
- }
-
- sleep_time();
- // 15. Admin Cert import Panel
- boolean disp_im = AdminCertImportPanel();
- if (!disp_im) {
- System.out
- .println("ERROR: ConfigureTPS: AdminCertImportPanel() failure");
- return false;
- }
-
- return true;
- }
-
- public static void main(String args[]) {
- ConfigureTPS ca = new ConfigureTPS();
-
- // set variables
- StringHolder x_cs_hostname = new StringHolder();
- StringHolder x_cs_port = new StringHolder();
- StringHolder x_cs_clientauth_port = new StringHolder();
-
- StringHolder x_sd_hostname = new StringHolder();
- StringHolder x_sd_ssl_port = new StringHolder();
- StringHolder x_sd_agent_port = new StringHolder();
- StringHolder x_sd_admin_port = new StringHolder();
- StringHolder x_sd_admin_name = new StringHolder();
- StringHolder x_sd_admin_password = new StringHolder();
-
- StringHolder x_ca_hostname = new StringHolder();
- StringHolder x_ca_port = new StringHolder();
- StringHolder x_ca_ssl_port = new StringHolder();
- StringHolder x_ca_admin_port = new StringHolder();
-
- StringHolder x_drm_hostname = new StringHolder();
- StringHolder x_drm_ssl_port = new StringHolder();
-
- StringHolder x_tks_hostname = new StringHolder();
- StringHolder x_tks_ssl_port = new StringHolder();
-
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_preop_pin = new StringHolder();
-
- StringHolder x_domain_name = new StringHolder();
-
- StringHolder x_admin_user = new StringHolder();
- StringHolder x_admin_email = new StringHolder();
- StringHolder x_admin_password = new StringHolder();
-
- // ldap
-
- StringHolder x_ldap_host = new StringHolder();
- StringHolder x_ldap_port = new StringHolder();
- StringHolder x_bind_dn = new StringHolder();
- StringHolder x_bind_password = new StringHolder();
- StringHolder x_base_dn = new StringHolder();
- StringHolder x_db_name = new StringHolder();
-
- StringHolder x_ldap_auth_host = new StringHolder();
- StringHolder x_ldap_auth_port = new StringHolder();
- StringHolder x_ldap_auth_base_dn = new StringHolder();
-
- // key size
- StringHolder x_token_name = new StringHolder();
- StringHolder x_token_pwd = new StringHolder();
- StringHolder x_key_size = new StringHolder();
- StringHolder x_key_type = new StringHolder();
-
- StringHolder x_agent_key_size = new StringHolder();
- StringHolder x_agent_key_type = new StringHolder();
- StringHolder x_agent_cert_subject = new StringHolder();
-
- StringHolder x_agent_name = new StringHolder();
-
- StringHolder x_ss_keygen = new StringHolder();
-
- // tps cert subject name params
- StringHolder x_tps_server_cert_subject_name = new StringHolder();
- StringHolder x_tps_server_cert_nickname = new StringHolder();
- StringHolder x_tps_subsystem_cert_subject_name = new StringHolder();
- StringHolder x_tps_subsystem_cert_nickname = new StringHolder();
- StringHolder x_tps_audit_signing_cert_subject_name = new StringHolder();
- StringHolder x_tps_audit_signing_cert_nickname = new StringHolder();
-
- // subsystemName
- StringHolder x_subsystem_name = new StringHolder();
-
- // parse the args
- ArgParser parser = new ArgParser("ConfigureTPS");
-
- parser.addOption("-cs_hostname %s #CS Hostname", x_cs_hostname);
- parser.addOption("-cs_port %s #CS SSL port", x_cs_port);
- parser.addOption("-cs_clientauth_port %s #CS SSL port",
- x_cs_clientauth_port);
-
- parser.addOption("-sd_hostname %s #Security Domain Hostname",
- x_sd_hostname);
- parser.addOption("-sd_ssl_port %s #Security Domain SSL EE port",
- x_sd_ssl_port);
- parser.addOption("-sd_agent_port %s #Security Domain SSL Agent port",
- x_sd_agent_port);
- parser.addOption("-sd_admin_port %s #Security Domain SSL Admin port",
- x_sd_admin_port);
- parser.addOption("-sd_admin_name %s #Security Domain username",
- x_sd_admin_name);
- parser.addOption("-sd_admin_password %s #Security Domain password",
- x_sd_admin_password);
-
- parser.addOption("-ca_hostname %s #CA Hostname", x_ca_hostname);
- parser.addOption("-ca_port %s #CA non-SSL port", x_ca_port);
- parser.addOption("-ca_ssl_port %s #CA SSL port", x_ca_ssl_port);
- parser.addOption("-ca_admin_port %s #CA SSL Admin port",
- x_ca_admin_port);
-
- parser.addOption("-drm_hostname %s #DRM Hostname", x_drm_hostname);
- parser.addOption("-drm_ssl_port %s #DRM SSL port", x_drm_ssl_port);
- parser.addOption(
- "-ss_keygen %s #Enable Server Side Keygen [true,false]",
- x_ss_keygen);
-
- parser.addOption("-tks_hostname %s #TKS Hostname", x_tks_hostname);
- parser.addOption("-tks_ssl_port %s #TKS SSL port", x_tks_ssl_port);
-
- parser.addOption("-client_certdb_dir %s #Client CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #client certdb password",
- x_client_certdb_pwd);
- parser.addOption("-preop_pin %s #pre op pin", x_preop_pin);
- parser.addOption("-domain_name %s #domain name", x_domain_name);
- parser.addOption("-admin_user %s #Admin User Name", x_admin_user);
- parser.addOption("-admin_email %s #Admin email", x_admin_email);
- parser.addOption("-admin_password %s #Admin password", x_admin_password);
- parser.addOption("-agent_name %s #Agent Cert Nickname", x_agent_name);
-
- parser.addOption("-ldap_host %s #ldap host", x_ldap_host);
- parser.addOption("-ldap_port %s #ldap port", x_ldap_port);
- parser.addOption("-bind_dn %s #ldap bind dn", x_bind_dn);
- parser.addOption("-bind_password %s #ldap bind password",
- x_bind_password);
- parser.addOption("-base_dn %s #base dn", x_base_dn);
- parser.addOption("-db_name %s #db name", x_db_name);
-
- parser.addOption("-token_name %s #HSM/Software Token name",
- x_token_name);
- parser.addOption(
- "-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
- x_token_pwd);
- parser.addOption("-key_size %s #Key Size", x_key_size);
- parser.addOption("-key_type %s #Key type [rsa,ecc]", x_key_type);
-
- parser.addOption("-agent_key_size %s #Agent Cert Key Size",
- x_agent_key_size);
- parser.addOption("-agent_key_type %s #Agent cert Key type [rsa]",
- x_agent_key_type);
- parser.addOption("-agent_cert_subject %s #Agent cert Subject",
- x_agent_cert_subject);
-
- parser.addOption("-ldap_auth_host %s #ldap auth host", x_ldap_auth_host);
- parser.addOption("-ldap_auth_port %s #ldap auth port", x_ldap_auth_port);
- parser.addOption("-ldap_auth_base_dn %s #ldap auth base dn",
- x_ldap_auth_base_dn);
-
- parser.addOption(
- "-tps_server_cert_subject_name %s #TPS server cert subject name",
- x_tps_server_cert_subject_name);
- parser.addOption(
- "-tps_server_cert_nickname %s #TPS server cert nickname",
- x_tps_server_cert_nickname);
- parser.addOption(
- "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name",
- x_tps_subsystem_cert_subject_name);
- parser.addOption(
- "-tps_subsystem_cert_nickname %s #TPS subsystem cert nickname",
- x_tps_subsystem_cert_nickname);
- parser.addOption(
- "-tps_audit_signing_cert_subject_name %s #TPS audit signing cert subject name",
- x_tps_audit_signing_cert_subject_name);
- parser.addOption(
- "-tps_audit_signing_cert_nickname %s #TPS audit signing cert nickname",
- x_tps_audit_signing_cert_nickname);
-
- parser.addOption("-subsystem_name %s #CA subsystem name",
- x_subsystem_name);
-
- // and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
-
- if (unmatched != null) {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- parser.checkRequiredArgs();
-
- // set variables
- cs_hostname = x_cs_hostname.value;
- cs_port = x_cs_port.value;
- cs_clientauth_port = x_cs_clientauth_port.value;
-
- sd_hostname = x_sd_hostname.value;
- sd_ssl_port = x_sd_ssl_port.value;
- sd_agent_port = x_sd_agent_port.value;
- sd_admin_port = x_sd_admin_port.value;
- sd_admin_name = x_sd_admin_name.value;
- sd_admin_password = x_sd_admin_password.value;
-
- ca_hostname = x_ca_hostname.value;
- ca_port = x_ca_port.value;
- ca_ssl_port = x_ca_ssl_port.value;
- ca_admin_port = x_ca_admin_port.value;
-
- tks_hostname = x_tks_hostname.value;
- tks_ssl_port = x_tks_ssl_port.value;
-
- drm_hostname = x_drm_hostname.value;
- drm_ssl_port = x_drm_ssl_port.value;
-
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- pin = x_preop_pin.value;
- domain_name = x_domain_name.value;
-
- admin_user = x_admin_user.value;
- admin_email = x_admin_email.value;
- admin_password = x_admin_password.value;
- agent_name = x_agent_name.value;
-
- ldap_host = x_ldap_host.value;
- ldap_port = x_ldap_port.value;
- bind_dn = x_bind_dn.value;
- bind_password = x_bind_password.value;
- base_dn = x_base_dn.value;
- db_name = x_db_name.value;
-
- ldap_auth_host = x_ldap_auth_host.value;
- ldap_auth_port = x_ldap_auth_port.value;
- ldap_auth_base_dn = x_ldap_auth_base_dn.value;
-
- key_size = x_key_size.value;
- key_type = x_key_type.value;
- token_name = x_token_name.value;
- token_pwd = x_token_pwd.value;
-
- agent_key_size = x_agent_key_size.value;
- agent_key_type = x_agent_key_type.value;
- agent_cert_subject = x_agent_cert_subject.value;
-
- ss_keygen = x_ss_keygen.value;
-
- tps_server_cert_subject_name = x_tps_server_cert_subject_name.value;
- tps_server_cert_nickname = x_tps_server_cert_nickname.value;
- tps_subsystem_cert_subject_name = x_tps_subsystem_cert_subject_name.value;
- tps_subsystem_cert_nickname = x_tps_subsystem_cert_nickname.value;
- tps_audit_signing_cert_subject_name = x_tps_audit_signing_cert_subject_name.value;
- tps_audit_signing_cert_nickname = x_tps_audit_signing_cert_nickname.value;
-
- subsystem_name = x_subsystem_name.value;
-
- boolean st = ca.ConfigureTPSInstance();
-
- if (!st) {
- System.out.println("ERROR: unable to create TPS");
- System.exit(-1);
- }
-
- System.out.println("Certificate System - TPS Instance Configured");
- System.exit(0);
-
- }
+ bais = new ByteArrayInputStream(
+ hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ st = true;
+ return st;
+ }
+
+ public boolean DomainPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String domain_url = "https://" + sd_hostname + ":" + sd_admin_port ;
+
+ String query_string = "p=3" +
+ "&choice=existingdomain" +
+ "&sdomainURL=" +
+ URLEncoder.encode(domain_url) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+
+ }
+
+ public boolean DisplayChainPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String query_string = null;
+
+ query_string = "p=4" + "&op=next" + "&xml=true";
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ return true;
+
+ }
+
+ public boolean SecurityDomainLoginPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String tps_url = "https://" + cs_hostname + ":" + cs_port +
+ "/tps/admin/console/config/wizard" +
+ "?p=3&subsystem=TPS" ;
+
+ String query_string = "url=" + URLEncoder.encode(tps_url) + "";
+
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_login_uri,query_string);
+
+ String query_string_1 = "uid=" + sd_admin_name +
+ "&pwd=" + URLEncoder.encode(sd_admin_password) +
+ "&url=" + URLEncoder.encode(tps_url) +
+ "" ;
+
+ hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ query_string_1);
+
+ // get session id from security domain
+ sleep_time();
+
+ tps_session_id = hr.getContentValue("header.session_id");
+ String tps_url_1 = hr.getContentValue("header.url");
+
+ System.out.println("TPS_SESSION_ID=" + tps_session_id );
+ System.out.println("TPS_URL=" + tps_url_1 );
+
+ // use session id to connect back to TPS
+
+ String query_string_2 = "p=5" +
+ "&subsystem=TPS" +
+ "&session_id=" + tps_session_id +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ query_string_2);
+
+ // parse xml - no parsing
+
+ return true;
+
+ }
+
+ public boolean SubsystemPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ sleep_time();
+ String query_string = "p=5" +
+ "&choice=newsubsystem" +
+ "&subsystemName=" +
+ URLEncoder.encode(subsystem_name) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+
+ // CA choice panel
+ query_string = "p=6" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ sleep_time();
+ // TKS choice panel
+ String tks_url = "https://" + tks_hostname + ":" + tks_ssl_port ;
+ query_string = "p=7" +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // DRM / server side keygen panel
+
+ sleep_time();
+ if(ss_keygen.equalsIgnoreCase("true"))
+ {
+ ss_keygen = "keygen";
+ }
+
+ String drm_url = "https://" + drm_hostname + ":" + drm_ssl_port ;
+
+ query_string = "p=8" +
+ "&choice=" + ss_keygen +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean LdapAuthConnectionPanel()
+ {
+ // auth db
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String query_string = "p=9" +
+ "&host=" +
+ URLEncoder.encode(ldap_auth_host) +
+ "&port=" +
+ URLEncoder.encode(ldap_auth_port) +
+ "&basedn=" +
+ URLEncoder.encode(ldap_auth_base_dn) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean LdapConnectionPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+
+ String query_string = "p=10" +
+ "&host=" +
+ URLEncoder.encode(ldap_host) +
+ "&port=" +
+ URLEncoder.encode(ldap_port) +
+ "&binddn=" +
+ URLEncoder.encode(bind_dn) +
+ "&__bindpwd=" +
+ URLEncoder.encode(bind_password) +
+ "&basedn=" +
+ URLEncoder.encode(base_dn) +
+ "&database=" +
+ URLEncoder.encode(db_name) +
+ "&display=" +
+ URLEncoder.encode("") +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean TokenChoicePanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+
+ ////////////////////////////////////////////////////////
+ String query_string = null;
+
+ // Software Token
+ if(token_name.equalsIgnoreCase("internal"))
+ {
+ query_string = "p=1" +
+ "&choice=" +
+ URLEncoder.encode("NSS Certificate DB") +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+ }
+ // HSM
+ else
+ {
+ // login to hsm first
+ query_string = "p=2" +
+ "&uTokName=" +
+ URLEncoder.encode(token_name) +
+ "&__uPasswd=" +
+ URLEncoder.encode(token_pwd) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // choice with token name now
+ query_string = "p=1" +
+ "&choice=" +
+ URLEncoder.encode(token_name) +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ }
+
+
+ return true;
+ }
+
+ public boolean KeyPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> friendly_list = null;
+ ArrayList<String> dn_list = null;
+
+
+ String query_string = "p=11" +
+ "&keytype=" + key_type +
+ "&choice=default" +
+ "&custom_size=" + key_size +
+ "&sslserver_keytype=" + key_type +
+ "&sslserver_choice=custom" +
+ "&sslserver_custom_size=" + key_size +
+ "&subsystem_keytype=" + key_type +
+ "&subsystem_choice=custom"+
+ "&subsystem_custom_size=" + key_size +
+ "&audit_signing_keytype=" + key_type +
+ "&audit_signing_choice=default" +
+ "&audit_signing_custom_size=" + key_size +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean CertSubjectPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+ ArrayList<String> friendly_list = null;
+
+ String ca_url = "https://" + ca_hostname + ":" + ca_ssl_port ;
+
+ String query_string = "p=12" +
+ "&sslserver=" +
+ URLEncoder.encode(tps_server_cert_subject_name) +
+ "&sslserver_nick=" +
+ URLEncoder.encode(tps_server_cert_nickname) +
+ "&subsystem=" +
+ URLEncoder.encode(tps_subsystem_cert_subject_name) +
+ "&subsystem_nick=" +
+ URLEncoder.encode(tps_subsystem_cert_nickname) +
+ "&audit_signing=" +
+ URLEncoder.encode(tps_audit_signing_cert_subject_name) +
+ "&audit_signing_nick=" +
+ URLEncoder.encode(tps_audit_signing_cert_nickname) +
+ "&urls=0" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ // parse the certs if needed
+
+ return true;
+ }
+
+ public boolean CertificatePanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ ArrayList<String> req_list = null;
+ ArrayList<String> cert_list = null;
+ ArrayList<String> dn_list = null;
+ ArrayList<String> pp_list = null;
+
+
+ String query_string = "p=13" +
+ "&sslserver=" +
+ "&sslserver_cc=" +
+ "&subsystem=" +
+ "&subsystem_cc=" +
+ "&audit_signing=" +
+ "&audit_signing_cc=" +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean AdminCertReqPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String admin_cert_request = null;
+
+ requestor_name = "TPS-" + cs_hostname + "-" + cs_clientauth_port;
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ agent_cert_subject,
+ agent_key_size,
+ agent_key_type);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.setTransportCert(null);
+ cCrypt.setDualKey(false);
+ cCrypt.loginDB();
+
+ String crmf_request = cCrypt.generateCRMFrequest();
+
+ if(crmf_request == null)
+ {
+ System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
+ return false;
+ }
+
+ admin_cert_request = crmf_request;
+
+ String query_string = "p=14" +
+ "&uid=" + admin_user +
+ "&name=" +
+ URLEncoder.encode("TPS Administrator") +
+ "&email=" +
+ URLEncoder.encode(admin_email) +
+ "&__pwd=" + URLEncoder.encode(admin_password) +
+ "&__admin_password_again=" + URLEncoder.encode(admin_password) +
+ "&cert_request=" +
+ URLEncoder.encode(admin_cert_request) +
+ "&display=0" +
+ "&profileId=" + "caAdminCert" +
+ "&cert_request_type=" + "crmf" +
+ "&import=true" +
+ "&uid=" + admin_user +
+ "&clone=0" +
+ "&securitydomain=" +
+ URLEncoder.encode(domain_name) +
+ "&subject=" +
+ URLEncoder.encode(agent_cert_subject) +
+ "&requestor_name=" +
+ URLEncoder.encode( requestor_name ) +
+ "&sessionID=" + tps_session_id +
+ "&auth_hostname=" + ca_hostname +
+ "&auth_port=" + ca_ssl_port +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ admin_serial_number = px.getvalue("serialNumber");
+
+ return true;
+ }
+
+ public boolean AdminCertImportPanel()
+ {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String cert_to_import = null;
+
+ String query_string = "serialNumber=" + admin_serial_number +
+ "&importCert=" + "true" +
+ "" ;
+
+ // NOTE: CA, DRM, OCSP, and TKS use the Security Domain Admin Port;
+ // whereas RA and TPS use the CA Admin Port associated with
+ // the 'CA choice panel' as invoked from the SubsystemPanel()
+ // which MAY or MAY NOT be the same CA as the CA specified
+ // by the Security Domain.
+ hr = hc.sslConnect(ca_hostname,ca_admin_port,admin_uri,query_string);
+
+ try
+ {
+ // cert_to_import =
+ // new sun.misc.BASE64Encoder().encode(hr.getResponseData());
+ cert_to_import =
+ OSUtil.BtoA(hr.getResponseData());
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("ERROR: failed to retrieve cert");
+ }
+
+ System.out.println("Imported Cert=" + cert_to_import);
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ String start = "-----BEGIN CERTIFICATE-----\r\n" ;
+ String end = "\r\n-----END CERTIFICATE-----" ;
+
+ st = cCrypt.importCert(start+cert_to_import+end,agent_name);
+ if(!st)
+ {
+ System.out.println("ERROR: AdminCertImportPanel() during cert import");
+ return false;
+ }
+
+ System.out.println("SUCCESS: imported admin user cert");
+
+ String query_string_1 = "p=15" +
+ "&serialNumber=" + admin_serial_number +
+ "&caHost=" +
+ URLEncoder.encode( ca_hostname ) +
+ "&caPort=" + ca_admin_port +
+ "&op=next" +
+ "&xml=true" ;
+
+ hr = hc.sslConnect( cs_hostname, cs_port, wizard_uri ,query_string_1 );
+
+ // parse xml
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
+
+ return true;
+ }
+
+ public boolean ConfigureTPSInstance()
+ {
+ // 0. login to cert db
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(true);
+ cCrypt.loginDB();
+
+ // instantiate http client
+ hc = new HTTPClient();
+
+ sleep_time();
+ // 1. Login panel
+ boolean log_st = LoginPanel();
+ if(!log_st)
+ {
+ System.out.println("ERROR: JSESSIONID not found.");
+ System.out.println("ERROR: ConfigureTPS: LoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 2. Token Choice Panel
+ boolean disp_token = TokenChoicePanel();
+ if(!disp_token)
+ {
+ System.out.println("ERROR: ConfigureTPS: TokenChoicePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 3. domain panel
+ boolean dom_st = DomainPanel();
+ if(!dom_st)
+ {
+ System.out.println("ERROR: ConfigureTPS: DomainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 4. display cert chain panel
+ boolean disp_st = DisplayChainPanel();
+ if(!disp_st)
+ {
+ System.out.println("ERROR: ConfigureTPS: DisplayChainPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 5. security domain login panel
+ boolean disp_sd = SecurityDomainLoginPanel();
+ if(!disp_sd)
+ {
+ System.out.println("ERROR: ConfigureTPS: SecurityDomainLoginPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 6. subsystem panel
+ boolean disp_ss = SubsystemPanel();
+ if(!disp_ss)
+ {
+ System.out.println("ERROR: ConfigureTPS: SubsystemPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 7. ldap auth connection panel
+ boolean disp_ldap_auth = LdapAuthConnectionPanel();
+ if(!disp_ldap_auth)
+ {
+ System.out.println("ERROR: ConfigureTPS: LdapAuthConnectionPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 8. ldap connection panel
+ boolean disp_ldap = LdapConnectionPanel();
+ if(!disp_ldap)
+ {
+ System.out.println("ERROR: ConfigureTPS: LdapConnectionPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 11. Key Panel
+ boolean disp_key = KeyPanel();
+ if(!disp_key)
+ {
+ System.out.println("ERROR: ConfigureTPS: KeyPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 12. Cert Subject Panel
+ boolean disp_csubj = CertSubjectPanel();
+ if(!disp_csubj)
+ {
+ System.out.println("ERROR: ConfigureTPS: CertSubjectPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 13. Certificate Panel
+ boolean disp_cp = CertificatePanel();
+ if(!disp_cp)
+ {
+ System.out.println("ERROR: ConfigureTPS: CertificatePanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 14. Admin Cert Req Panel
+ boolean disp_adm = AdminCertReqPanel();
+ if(!disp_adm)
+ {
+ System.out.println("ERROR: ConfigureTPS: AdminCertReqPanel() failure");
+ return false;
+ }
+
+ sleep_time();
+ // 15. Admin Cert import Panel
+ boolean disp_im = AdminCertImportPanel();
+ if(!disp_im)
+ {
+ System.out.println("ERROR: ConfigureTPS: AdminCertImportPanel() failure");
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String args[])
+ {
+ ConfigureTPS ca = new ConfigureTPS();
+
+ // set variables
+ StringHolder x_cs_hostname = new StringHolder();
+ StringHolder x_cs_port = new StringHolder();
+ StringHolder x_cs_clientauth_port = new StringHolder();
+
+ StringHolder x_sd_hostname = new StringHolder();
+ StringHolder x_sd_ssl_port = new StringHolder();
+ StringHolder x_sd_agent_port = new StringHolder();
+ StringHolder x_sd_admin_port = new StringHolder();
+ StringHolder x_sd_admin_name = new StringHolder();
+ StringHolder x_sd_admin_password = new StringHolder();
+
+ StringHolder x_ca_hostname = new StringHolder();
+ StringHolder x_ca_port = new StringHolder();
+ StringHolder x_ca_ssl_port = new StringHolder();
+ StringHolder x_ca_admin_port = new StringHolder();
+
+ StringHolder x_drm_hostname = new StringHolder();
+ StringHolder x_drm_ssl_port = new StringHolder();
+
+ StringHolder x_tks_hostname = new StringHolder();
+ StringHolder x_tks_ssl_port = new StringHolder();
+
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_preop_pin = new StringHolder();
+
+ StringHolder x_domain_name = new StringHolder();
+
+ StringHolder x_admin_user = new StringHolder();
+ StringHolder x_admin_email = new StringHolder();
+ StringHolder x_admin_password = new StringHolder();
+
+ // ldap
+
+ StringHolder x_ldap_host = new StringHolder();
+ StringHolder x_ldap_port = new StringHolder();
+ StringHolder x_bind_dn = new StringHolder();
+ StringHolder x_bind_password = new StringHolder();
+ StringHolder x_base_dn = new StringHolder();
+ StringHolder x_db_name = new StringHolder();
+
+ StringHolder x_ldap_auth_host = new StringHolder();
+ StringHolder x_ldap_auth_port = new StringHolder();
+ StringHolder x_ldap_auth_base_dn = new StringHolder();
+
+ // key size
+ StringHolder x_token_name = new StringHolder();
+ StringHolder x_token_pwd = new StringHolder();
+ StringHolder x_key_size = new StringHolder();
+ StringHolder x_key_type = new StringHolder();
+
+ StringHolder x_agent_key_size = new StringHolder();
+ StringHolder x_agent_key_type = new StringHolder();
+ StringHolder x_agent_cert_subject = new StringHolder();
+
+ StringHolder x_agent_name = new StringHolder();
+
+ StringHolder x_ss_keygen = new StringHolder();
+
+ // tps cert subject name params
+ StringHolder x_tps_server_cert_subject_name = new StringHolder();
+ StringHolder x_tps_server_cert_nickname = new StringHolder();
+ StringHolder x_tps_subsystem_cert_subject_name = new StringHolder();
+ StringHolder x_tps_subsystem_cert_nickname = new StringHolder();
+ StringHolder x_tps_audit_signing_cert_subject_name = new StringHolder();
+ StringHolder x_tps_audit_signing_cert_nickname = new StringHolder();
+
+ // subsystemName
+ StringHolder x_subsystem_name = new StringHolder();
+
+
+ // parse the args
+ ArgParser parser = new ArgParser("ConfigureTPS");
+
+ parser.addOption ("-cs_hostname %s #CS Hostname",
+ x_cs_hostname);
+ parser.addOption ("-cs_port %s #CS SSL port",
+ x_cs_port);
+ parser.addOption ("-cs_clientauth_port %s #CS SSL port",
+ x_cs_clientauth_port);
+
+ parser.addOption ("-sd_hostname %s #Security Domain Hostname",
+ x_sd_hostname);
+ parser.addOption ("-sd_ssl_port %s #Security Domain SSL EE port",
+ x_sd_ssl_port);
+ parser.addOption ("-sd_agent_port %s #Security Domain SSL Agent port",
+ x_sd_agent_port);
+ parser.addOption ("-sd_admin_port %s #Security Domain SSL Admin port",
+ x_sd_admin_port);
+ parser.addOption ("-sd_admin_name %s #Security Domain username",
+ x_sd_admin_name);
+ parser.addOption ("-sd_admin_password %s #Security Domain password",
+ x_sd_admin_password);
+
+ parser.addOption ("-ca_hostname %s #CA Hostname",
+ x_ca_hostname);
+ parser.addOption ("-ca_port %s #CA non-SSL port",
+ x_ca_port);
+ parser.addOption ("-ca_ssl_port %s #CA SSL port",
+ x_ca_ssl_port);
+ parser.addOption ("-ca_admin_port %s #CA SSL Admin port",
+ x_ca_admin_port);
+
+ parser.addOption ("-drm_hostname %s #DRM Hostname",
+ x_drm_hostname);
+ parser.addOption ("-drm_ssl_port %s #DRM SSL port",
+ x_drm_ssl_port);
+ parser.addOption ("-ss_keygen %s #Enable Server Side Keygen [true,false]",
+ x_ss_keygen);
+
+ parser.addOption ("-tks_hostname %s #TKS Hostname",
+ x_tks_hostname);
+ parser.addOption ("-tks_ssl_port %s #TKS SSL port",
+ x_tks_ssl_port);
+
+ parser.addOption ("-client_certdb_dir %s #Client CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #client certdb password",
+ x_client_certdb_pwd);
+ parser.addOption ("-preop_pin %s #pre op pin",
+ x_preop_pin);
+ parser.addOption ("-domain_name %s #domain name",
+ x_domain_name);
+ parser.addOption ("-admin_user %s #Admin User Name",
+ x_admin_user);
+ parser.addOption ("-admin_email %s #Admin email",
+ x_admin_email);
+ parser.addOption ("-admin_password %s #Admin password",
+ x_admin_password);
+ parser.addOption ("-agent_name %s #Agent Cert Nickname",
+ x_agent_name);
+
+ parser.addOption ("-ldap_host %s #ldap host",
+ x_ldap_host);
+ parser.addOption ("-ldap_port %s #ldap port",
+ x_ldap_port);
+ parser.addOption ("-bind_dn %s #ldap bind dn",
+ x_bind_dn);
+ parser.addOption ("-bind_password %s #ldap bind password",
+ x_bind_password);
+ parser.addOption ("-base_dn %s #base dn",
+ x_base_dn);
+ parser.addOption ("-db_name %s #db name",
+ x_db_name);
+
+ parser.addOption ("-token_name %s #HSM/Software Token name",
+ x_token_name);
+ parser.addOption ("-token_pwd %s #HSM/Software Token password (optional, required for HSM)",
+ x_token_pwd);
+ parser.addOption ("-key_size %s #Key Size",
+ x_key_size);
+ parser.addOption ("-key_type %s #Key type [rsa,ecc]",
+ x_key_type);
+
+ parser.addOption ("-agent_key_size %s #Agent Cert Key Size",
+ x_agent_key_size);
+ parser.addOption ("-agent_key_type %s #Agent cert Key type [rsa]",
+ x_agent_key_type);
+ parser.addOption ("-agent_cert_subject %s #Agent cert Subject",
+ x_agent_cert_subject);
+
+
+ parser.addOption ("-ldap_auth_host %s #ldap auth host",
+ x_ldap_auth_host);
+ parser.addOption ("-ldap_auth_port %s #ldap auth port",
+ x_ldap_auth_port);
+ parser.addOption ("-ldap_auth_base_dn %s #ldap auth base dn",
+ x_ldap_auth_base_dn);
+
+ parser.addOption (
+ "-tps_server_cert_subject_name %s #TPS server cert subject name",
+ x_tps_server_cert_subject_name);
+ parser.addOption (
+ "-tps_server_cert_nickname %s #TPS server cert nickname",
+ x_tps_server_cert_nickname);
+ parser.addOption (
+ "-tps_subsystem_cert_subject_name %s #TPS subsystem cert subject name",
+ x_tps_subsystem_cert_subject_name);
+ parser.addOption (
+ "-tps_subsystem_cert_nickname %s #TPS subsystem cert nickname",
+ x_tps_subsystem_cert_nickname);
+ parser.addOption(
+ "-tps_audit_signing_cert_subject_name %s #TPS audit signing cert subject name",
+ x_tps_audit_signing_cert_subject_name);
+ parser.addOption(
+ "-tps_audit_signing_cert_nickname %s #TPS audit signing cert nickname",
+ x_tps_audit_signing_cert_nickname);
+
+ parser.addOption (
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
+
+
+ // and then match the arguments
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+
+ if(unmatched!=null)
+ {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ parser.checkRequiredArgs();
+
+ // set variables
+ cs_hostname = x_cs_hostname.value;
+ cs_port = x_cs_port.value;
+ cs_clientauth_port = x_cs_clientauth_port.value;
+
+ sd_hostname = x_sd_hostname.value;
+ sd_ssl_port = x_sd_ssl_port.value;
+ sd_agent_port = x_sd_agent_port.value;
+ sd_admin_port = x_sd_admin_port.value;
+ sd_admin_name = x_sd_admin_name.value;
+ sd_admin_password = x_sd_admin_password.value;
+
+ ca_hostname = x_ca_hostname.value;
+ ca_port = x_ca_port.value;
+ ca_ssl_port = x_ca_ssl_port.value;
+ ca_admin_port = x_ca_admin_port.value;
+
+ tks_hostname = x_tks_hostname.value;
+ tks_ssl_port = x_tks_ssl_port.value;
+
+ drm_hostname = x_drm_hostname.value;
+ drm_ssl_port = x_drm_ssl_port.value;
+
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ pin = x_preop_pin.value;
+ domain_name = x_domain_name.value;
+
+ admin_user = x_admin_user.value;
+ admin_email = x_admin_email.value;
+ admin_password = x_admin_password.value;
+ agent_name = x_agent_name.value;
+
+ ldap_host = x_ldap_host.value;
+ ldap_port = x_ldap_port.value;
+ bind_dn = x_bind_dn.value;
+ bind_password = x_bind_password.value;
+ base_dn = x_base_dn.value;
+ db_name = x_db_name.value;
+
+ ldap_auth_host = x_ldap_auth_host.value;
+ ldap_auth_port = x_ldap_auth_port.value;
+ ldap_auth_base_dn = x_ldap_auth_base_dn.value;
+
+ key_size = x_key_size.value;
+ key_type = x_key_type.value;
+ token_name = x_token_name.value;
+ token_pwd = x_token_pwd.value;
+
+ agent_key_size = x_agent_key_size.value;
+ agent_key_type = x_agent_key_type.value;
+ agent_cert_subject = x_agent_cert_subject.value;
+
+ ss_keygen = x_ss_keygen.value;
+
+ tps_server_cert_subject_name =
+ x_tps_server_cert_subject_name.value ;
+ tps_server_cert_nickname =
+ x_tps_server_cert_nickname.value ;
+ tps_subsystem_cert_subject_name =
+ x_tps_subsystem_cert_subject_name.value;
+ tps_subsystem_cert_nickname =
+ x_tps_subsystem_cert_nickname.value;
+ tps_audit_signing_cert_subject_name =
+ x_tps_audit_signing_cert_subject_name.value;
+ tps_audit_signing_cert_nickname =
+ x_tps_audit_signing_cert_nickname.value;
+
+ subsystem_name = x_subsystem_name.value ;
+
+
+
+ boolean st = ca.ConfigureTPSInstance();
+
+ if (!st)
+ {
+ System.out.println("ERROR: unable to create TPS");
+ System.exit(-1);
+ }
+
+ System.out.println("Certificate System - TPS Instance Configured");
+ System.exit(0);
+
+ }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java b/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
index d86ba84b..c1a9a7be 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -22,6 +21,7 @@ import java.net.URLEncoder;
import com.netscape.pkisilent.common.PostQuery;
+
public class CreateInstance {
private static String host;
@@ -95,18 +95,20 @@ public class CreateInstance {
adminDomain = args[8];
}
-
+
boolean st = newinstance.CreateInstance();
if (!st) {
- System.out
- .println("ERROR: Certificate System - Instance NOT created");
+ System.out.println("ERROR: Certificate System - Instance NOT created");
System.exit(-1);
}
System.out.println("Certificate System - Instance created");
System.exit(0);
-
+
}
-};
+}
+
+
+;
diff --git a/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java b/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
index 70528023..e61af61f 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
@@ -4,56 +4,57 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
+
public class PKISilent {
- private static void usage() {
- System.out.print("usage: java " + PKISilent.class.getCanonicalName());
- boolean first = true;
- for (Class<?> c : classes) {
- if (first) {
- System.out.println(" [ ");
- } else {
- System.out.println(" | ");
- }
- first = false;
- System.out.print(" " + c.getSimpleName());
- }
- System.out.println(" ] ");
- }
+ private static void usage() {
+ System.out.print("usage: java " + PKISilent.class.getCanonicalName());
+ boolean first = true;
+ for (Class<?> c : classes) {
+ if (first) {
+ System.out.println(" [ ");
+ } else {
+ System.out.println(" | ");
+ }
+ first = false;
+ System.out.print(" " + c.getSimpleName());
+ }
+ System.out.println(" ] ");
+ }
- static Class<?>[] classes = { ConfigureCA.class, ConfigureDRM.class,
- ConfigureOCSP.class, ConfigureRA.class, ConfigureSubCA.class,
- ConfigureTKS.class, ConfigureTPS.class, CreateInstance.class, };
+ static Class<?>[] classes = { ConfigureCA.class, ConfigureDRM.class,
+ ConfigureOCSP.class, ConfigureRA.class, ConfigureSubCA.class,
+ ConfigureTKS.class, ConfigureTPS.class, CreateInstance.class, };
- public static final void main(String[] args) {
- HashMap<String, Method> classMap = new HashMap<String, Method>();
- for (Class<?> c : classes) {
- try {
- classMap.put(c.getSimpleName(),
- c.getMethod("main", String[].class));
- } catch (Exception e) {
- // The set of classes listed above is guaranteed to have a
- // method 'main'
- e.printStackTrace();
- }
- }
- if (args.length == 0) {
- usage();
- System.exit(-1);
- }
- Method mainMethod = classMap.get(args[0]);
- if (mainMethod == null) {
- usage();
- System.exit(-1);
- }
- String[] innerArgs = {};
- if (args.length > 1) {
- innerArgs = Arrays.copyOfRange(args, 1, args.length);
- }
+ public static final void main(String[] args) {
+ HashMap<String, Method> classMap = new HashMap<String, Method>();
+ for (Class<?> c : classes) {
+ try {
+ classMap.put(c.getSimpleName(),
+ c.getMethod("main", String[].class));
+ } catch (Exception e) {
+ // The set of classes listed above is guaranteed to have a
+ // method 'main'
+ e.printStackTrace();
+ }
+ }
+ if (args.length == 0) {
+ usage();
+ System.exit(-1);
+ }
+ Method mainMethod = classMap.get(args[0]);
+ if (mainMethod == null) {
+ usage();
+ System.exit(-1);
+ }
+ String[] innerArgs = {};
+ if (args.length > 1) {
+ innerArgs = Arrays.copyOfRange(args, 1, args.length);
+ }
- try {
- mainMethod.invoke(null, (Object) innerArgs);
- } catch (Exception e) {
- // exception is guaranteed to have the static main method
- }
- }
+ try {
+ mainMethod.invoke(null, (Object) innerArgs);
+ } catch (Exception e) {
+ // exception is guaranteed to have the static main method
+ }
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
index 3a78e5ce..c2b927cc 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,35 +18,37 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
import java.io.IOException;
-/**
- * Exception class used by <code>ArgParser</code> when command line arguments
- * contain an error.
- *
- * @author John E. Lloyd, Fall 2004
- * @see ArgParser
- */
-public class ArgParseException extends IOException {
- /**
+/**
+ * Exception class used by <code>ArgParser</code> when
+ * command line arguments contain an error.
+ *
+ * @author John E. Lloyd, Fall 2004
+ * @see ArgParser
+ */
+public class ArgParseException extends IOException
+{
+ /**
*
*/
private static final long serialVersionUID = -604960834535589460L;
/**
- * Creates a new ArgParseException with the given message.
- *
- * @param msg Exception message
- */
- public ArgParseException(String msg) {
- super(msg);
- }
+ * Creates a new ArgParseException with the given message.
+ *
+ * @param msg Exception message
+ */
+ public ArgParseException (String msg)
+ { super (msg);
+ }
- /**
- * Creates a new ArgParseException from the given argument and message.
- *
- * @param arg Offending argument
- * @param msg Error message
- */
- public ArgParseException(String arg, String msg) {
- super(arg + ": " + msg);
- }
+ /**
+ * Creates a new ArgParseException from the given
+ * argument and message.
+ *
+ * @param arg Offending argument
+ * @param msg Error message
+ */
+ public ArgParseException (String arg, String msg)
+ { super (arg + ": " + msg);
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
index e396d6f5..a205d101 100755
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,17 +18,17 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
- * copy, modify and redistribute is granted, provided that this copyright
- * notice is retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including
- * any implied warranty of merchantability or fitness for a particular
- * use. The author assumes no responsibility for, and shall not be liable
- * for, any special, indirect, or consequential damages, or any damages
- * whatsoever, arising out of or in connection with the use of this
- * software.
- */
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
+ * copy, modify and redistribute is granted, provided that this copyright
+ * notice is retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including
+ * any implied warranty of merchantability or fitness for a particular
+ * use. The author assumes no responsibility for, and shall not be liable
+ * for, any special, indirect, or consequential damages, or any damages
+ * whatsoever, arising out of or in connection with the use of this
+ * software.
+ */
import java.io.File;
import java.io.FileReader;
@@ -41,200 +40,191 @@ import java.lang.reflect.Array;
import java.util.Vector;
/**
- * ArgParser is used to parse the command line arguments for a java application
- * program. It provides a compact way to specify options and match them against
- * command line arguments, with support for <a href=#rangespec>range
- * checking</a>, <a href=#multipleOptionNames>multiple option names</a>
- * (aliases), <a href=#singleWordOptions>single word options</a>, <a
- * href=#multipleOptionValues>multiple values associated with an option</a>, <a
- * href=#multipleOptionInvocation>multiple option invocation</a>, <a
- * href=#helpInfo>generating help information</a>, <a
- * href=#customArgParsing>custom argument parsing</a>, and <a
- * href=#argsFromAFile>reading arguments from a file</a>. The last feature is
- * particularly useful and makes it easy to create ad-hoc configuration files
- * for an application.
- *
+ * ArgParser is used to parse the command line arguments for a java
+ * application program. It provides a compact way to specify options and match
+ * them against command line arguments, with support for
+ * <a href=#rangespec>range checking</a>,
+ * <a href=#multipleOptionNames>multiple option names</a> (aliases),
+ * <a href=#singleWordOptions>single word options</a>,
+ * <a href=#multipleOptionValues>multiple values associated with an option</a>,
+ * <a href=#multipleOptionInvocation>multiple option invocation</a>,
+ * <a href=#helpInfo>generating help information</a>,
+ * <a href=#customArgParsing>custom argument parsing</a>, and
+ * <a href=#argsFromAFile>reading arguments from a file</a>. The
+ * last feature is particularly useful and makes it
+ * easy to create ad-hoc configuration files for an application.
+ *
* <h3><a name="example">Basic Example</a></h3>
- *
- * <p>
- * Here is a simple example in which an application has three command line
- * options: <code>-theta</code> (followed by a floating point value),
- * <code>-file</code> (followed by a string value), and <code>-debug</code>,
- * which causes a boolean value to be set.
+ *
+ * <p>Here is a simple example in which an application has three
+ * command line options:
+ * <code>-theta</code> (followed by a floating point value),
+ * <code>-file</code> (followed by a string value), and
+ * <code>-debug</code>, which causes a boolean value to be set.
*
* <pre>
+ *
+ * static public void main (String[] args)
+ * {
+ * // create holder objects for storing results ...
*
- * static public void main(String[] args) {
- * // create holder objects for storing results ...
- *
- * DoubleHolder theta = new DoubleHolder();
- * StringHolder fileName = new StringHolder();
- * BooleanHolder debug = new BooleanHolder();
- *
- * // create the parser and specify the allowed options ...
- *
- * ArgParser parser = new ArgParser(&quot;java argparser.SimpleExample&quot;);
- * parser.addOption(&quot;-theta %f #theta value (in degrees)&quot;, theta);
- * parser.addOption(&quot;-file %s #name of the operating file&quot;, fileName);
- * parser.addOption(&quot;-debug %v #enables display of debugging info&quot;, debug);
- *
- * // match the arguments ...
+ * DoubleHolder theta = new DoubleHolder();
+ * StringHolder fileName = new StringHolder();
+ * BooleanHolder debug = new BooleanHolder();
*
- * parser.matchAllArgs(args);
+ * // create the parser and specify the allowed options ...
*
- * // and print out the values
+ * ArgParser parser = new ArgParser("java argparser.SimpleExample");
+ * parser.addOption ("-theta %f #theta value (in degrees)", theta);
+ * parser.addOption ("-file %s #name of the operating file", fileName);
+ * parser.addOption ("-debug %v #enables display of debugging info", debug);
+ *
+ * // match the arguments ...
*
- * System.out.println(&quot;theta=&quot; + theta.value);
- * System.out.println(&quot;fileName=&quot; + fileName.value);
- * System.out.println(&quot;debug=&quot; + debug.value);
- * }
+ * parser.matchAllArgs (args);
+ *
+ * // and print out the values
+ *
+ * System.out.println ("theta=" + theta.value);
+ * System.out.println ("fileName=" + fileName.value);
+ * System.out.println ("debug=" + debug.value);
+ * }
* </pre>
- * <p>
- * A command line specifying all three options might look like this:
- *
+ * <p>A command line specifying all three options might look like this:
* <pre>
- * java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar
+ * java argparser.SimpleExample -theta 7.8 -debug -file /ai/lloyd/bar
* </pre>
*
- * <p>
- * The application creates an instance of ArgParser and then adds descriptions
- * of the allowed options using {@link #addOption addOption}. The method
- * {@link #matchAllArgs(String[]) matchAllArgs} is then used to match these
- * options against the command line arguments. Values associated with each
- * option are returned in the <code>value</code> field of special ``holder''
- * classes (e.g., {@link argparser.DoubleHolder DoubleHolder},
+ * <p>The application creates an instance of ArgParser and then adds
+ * descriptions of the allowed options using {@link #addOption addOption}. The
+ * method {@link #matchAllArgs(String[]) matchAllArgs} is then used to match
+ * these options against the command line arguments. Values associated with
+ * each option are returned in the <code>value</code> field of special
+ * ``holder'' classes (e.g., {@link argparser.DoubleHolder DoubleHolder},
* {@link argparser.StringHolder StringHolder}, etc.).
- *
- * <p>
- * The first argument to {@link #addOption addOption} is a string that specifies
- * (1) the option's name, (2) a conversion code for its associated value (e.g.,
- * <code>%f</code> for floating point, <code>%s</code> for a string,
- * <code>%v</code> for a boolean flag), and (3) an optional description
+ *
+ * <p> The first argument to {@link #addOption addOption} is a string that
+ * specifies (1) the option's name, (2) a conversion code for its associated
+ * value (e.g., <code>%f</code> for floating point, <code>%s</code> for a
+ * string, <code>%v</code> for a boolean flag), and (3) an optional description
* (following the <code>#</code> character) which is used for generating help
- * messages. The second argument is the holder object through which the value is
- * returned. This may be either a type-specific object (such as
- * {@link argparser.DoubleHolder DoubleHolder} or {@link argparser.StringHolder
- * StringHolder}), an array of the appropriate type, or <a
- * href=#multipleOptionInvocation> an instance of <code>java.util.Vector</code>
- * </a>.
- *
- * <p>
- * By default, arguments that don't match the specified options, are <a
+ * messages. The second argument is the holder object through which the value
+ * is returned. This may be either a type-specific object (such as {@link
+ * argparser.DoubleHolder DoubleHolder} or {@link argparser.StringHolder
+ * StringHolder}), an array of the appropriate type, or
+ * <a href=#multipleOptionInvocation> an instance of
+ * <code>java.util.Vector</code></a>.
+ *
+ * <p>By default, arguments that don't match the specified options, are <a
* href=#rangespec>out of range</a>, or are otherwise formatted incorrectly,
- * will cause <code>matchAllArgs</code> to print a message and exit the program.
- * Alternatively, an application can use {@link #matchAllArgs(String[],int,int)
- * matchAllArgs(args,idx,exitFlags)} to obtain an array of unmatched arguments
- * which can then be <a href=#customArgParsing>processed separately</a>
- *
+ * will cause <code>matchAllArgs</code> to print a message and exit the
+ * program. Alternatively, an application can use {@link
+ * #matchAllArgs(String[],int,int) matchAllArgs(args,idx,exitFlags)} to obtain
+ * an array of unmatched arguments which can then be
+ * <a href=#customArgParsing>processed separately</a>
+ *
* <h3><a name="rangespec">Range Specification</a></h3>
- *
+ *
* The values associated with options can also be given range specifications. A
* range specification appears in curly braces immediately following the
- * conversion code. In the code fragment below, we show how to specify an option
- * <code>-name</code> that expects to be provided with one of three string
- * values (<code>john</code>, <code>mary</code>, or <code>jane</code>), an
- * option <code>-index</code> that expects to be supplied with a integer value
- * in the range 1 to 256, an option <code>-size</code> that expects to be
+ * conversion code. In the code fragment below, we show how to specify an
+ * option <code>-name</code> that expects to be provided with one of three
+ * string values (<code>john</code>, <code>mary</code>, or <code>jane</code>),
+ * an option <code>-index</code> that expects to be supplied with a integer
+ * value in the range 1 to 256, an option <code>-size</code> that expects to be
* supplied with integer values of either 1, 2, 4, 8, or 16, and an option
* <code>-foo</code> that expects to be supplied with floating point values in
* the ranges -99 < foo <= -50, or 50 <= foo < 99.
- *
+ *
* <pre>
- * StringHolder name = new StringHolder();
- * IntHolder index = new IntHolder();
- * IntHolder size = new IntHolder();
- * DoubleHolder foo = new DoubleHolder();
- *
- * parser.addOption(&quot;-name %s {john,mary,jane}&quot;, name);
- * parser.addOption(&quot;-index %d {[1,256]}&quot;, index);
- * parser.addOption(&quot;-size %d {1,2,4,8,16}&quot;, size);
- * parser.addOption(&quot;-foo %f {(-99,-50],[50,99)}&quot;, foo);
+ * StringHolder name = new StringHolder();
+ * IntHolder index = new IntHolder();
+ * IntHolder size = new IntHolder();
+ * DoubleHolder foo = new DoubleHolder();
+ *
+ * parser.addOption ("-name %s {john,mary,jane}", name);
+ * parser.addOption ("-index %d {[1,256]}", index);
+ * parser.addOption ("-size %d {1,2,4,8,16}", size);
+ * parser.addOption ("-foo %f {(-99,-50],[50,99)}", foo);
* </pre>
- *
+ *
* If an argument value does not lie within a specified range, an error is
* generated.
- *
+ *
* <h3><a name="multipleOptionNames">Multiple Option Names</a></h3>
- *
- * An option may be given several names, or aliases, in the form of a comma
- * seperated list:
- *
+ *
+ * An option may be given several names, or aliases, in the form of
+ * a comma seperated list:
+ *
* <pre>
- * parser.addOption(&quot;-v,--verbose %v #print lots of info&quot;);
- * parser.addOption(&quot;-of,-outfile,-outputFile %s #output file&quot;);
+ * parser.addOption ("-v,--verbose %v #print lots of info");
+ * parser.addOption ("-of,-outfile,-outputFile %s #output file");
* </pre>
- *
+ *
* <h3><a name="singleWordOptions">Single Word Options</a></h3>
- *
- * Normally, options are assumed to be "multi-word", meaning that any associated
- * value must follow the option as a separate argument string. For example,
- *
+ *
+ * Normally, options are assumed to be "multi-word", meaning
+ * that any associated value must follow the option as a
+ * separate argument string. For
+ * example,
* <pre>
- * parser.addOption(&quot;-file %s #file name&quot;);
+ * parser.addOption ("-file %s #file name");
* </pre>
- *
- * will cause the parser to look for two strings in the argument list of the
- * form
- *
+ * will cause the parser to look for two strings in the argument list
+ * of the form
* <pre>
* -file someFileName
* </pre>
- *
- * However, if there is no white space separting the option's name from it's
- * conversion code, then values associated with that option will be assumed to
- * be part of the same argument string as the option itself. For example,
- *
+ * However, if there is no white space separting the option's name from
+ * it's conversion code, then values associated with that
+ * option will be assumed to be part of the same argument
+ * string as the option itself. For example,
* <pre>
- * parser.addOption(&quot;-file=%s #file name&quot;);
+ * parser.addOption ("-file=%s #file name");
* </pre>
- *
- * will cause the parser to look for a single string in the argument list of the
- * form
- *
+ * will cause the parser to look for a single string in the argument
+ * list of the form
* <pre>
* -file=someFileName
* </pre>
- *
* Such an option is called a "single word" option.
- *
+ *
* <p>
- * In cases where an option has multiple names, then this single word behavior
- * is invoked if there is no white space between the last indicated name and the
- * conversion code. However, previous names in the list will still be given
- * multi-word behavior if there is white space between the name and the
+ * In cases where an option has multiple names, then this single
+ * word behavior is invoked if there is no white space between
+ * the last indicated name and the conversion code. However, previous
+ * names in the list will still be given multi-word behavior
+ * if there is white space between the name and the
* following comma. For example,
- *
* <pre>
- * parser.addOption(&quot;-nb=,-number ,-n%d #number of blocks&quot;);
+ * parser.addOption ("-nb=,-number ,-n%d #number of blocks");
* </pre>
- *
- * will cause the parser to look for one, two, and one word constructions of the
- * forms
- *
+ * will cause the parser to look for one, two, and one word constructions
+ * of the forms
* <pre>
* -nb=N
* -number N
* -nN
* </pre>
- *
+ *
* <h3><a name="multipleOptionValues">Multiple Option Values</a></h3>
- *
- * If may be useful for an option to be followed by several values. For
- * instance, we might have an option <code>-velocity</code> which should be
- * followed by three numbers denoting the x, y, and z components of a velocity
- * vector. We can require multiple values for an option by placing a
- * <i>multiplier</i> specification, of the form <code>X</code>N, where N is an
- * integer, after the conversion code (or range specification, if present). For
- * example,
+ *
+ * If may be useful for an option to be followed by several values.
+ * For instance, we might have an option <code>-velocity</code>
+ * which should be followed by three numbers denoting
+ * the x, y, and z components of a velocity vector.
+ * We can require multiple values for an option
+ * by placing a <i>multiplier</i> specification,
+ * of the form <code>X</code>N, where N is an integer,
+ * after the conversion code (or range specification, if present).
+ * For example,
*
* <pre>
- * double[] pos = new double[3];
- *
- * addOption(&quot;-position %fX3 #position of the object&quot;, pos);
+ * double[] pos = new double[3];
+ *
+ * addOption ("-position %fX3 #position of the object", pos);
* </pre>
- *
* will cause the parser to look for
- *
* <pre>
* -position xx yy zz
* </pre>
@@ -242,53 +232,52 @@ import java.util.Vector;
* in the argument list, where <code>xx</code>, <code>yy</code>, and
* <code>zz</code> are numbers. The values are stored in the array
* <code>pos</code>.
- *
- * Options requiring multiple values must use arrays to return their values, and
- * cannot be used in single word format.
- *
+ *
+ * Options requiring multiple values must use arrays to
+ * return their values, and cannot be used in single word format.
+ *
* <h3><a name="multipleOptionInvocation">Multiple Option Invocation</a></h3>
- *
- * Normally, if an option appears twice in the command list, the value
- * associated with the second instance simply overwrites the value associated
- * with the first instance.
- *
+ *
+ * Normally, if an option appears twice in the command list, the
+ * value associated with the second instance simply overwrites the
+ * value associated with the first instance.
+ *
* However, the application can instead arrange for the storage of <i>all</i>
- * values associated with multiple option invocation, by supplying a instance of
- * <code>java.util.Vector</code> to serve as the value holder. Then every time
- * the option appears in the argument list, the parser will create a value
- * holder of appropriate type, set it to the current value, and store the holder
- * in the vector. For example, the construction
- *
+ * values associated with multiple option invocation, by supplying a instance
+ * of <code>java.util.Vector</code> to serve as the value holder. Then every
+ * time the option appears in the argument list, the parser will create a value
+ * holder of appropriate type, set it to the current value, and store the
+ * holder in the vector. For example, the construction
+ *
* <pre>
- * Vector vec = new Vector(10);
- *
- * parser.addOption(&quot;-foo %f&quot;, vec);
- * parser.matchAllArgs(args);
+ * Vector vec = new Vector(10);
+ *
+ * parser.addOption ("-foo %f", vec);
+ * parser.matchAllArgs(args);
* </pre>
- *
* when supplied with an argument list that contains
- *
* <pre>
* -foo 1.2 -foo 1000 -foo -78
* </pre>
*
* will create three instances of {@link argparser.DoubleHolder DoubleHolder},
- * initialized to <code>1.2</code>, <code>1000</code>, and <code>-78</code>, and
- * store them in <code>vec</code>.
- *
+ * initialized to <code>1.2</code>, <code>1000</code>, and <code>-78</code>,
+ * and store them in <code>vec</code>.
+ *
* <h3><a name="helpInfo">Generating help information</a></h3>
- *
+ *
* ArgParser automatically generates help information for the options, and this
* information may be printed in response to a <i>help</i> option, or may be
- * queried by the application using {@link #getHelpMessage getHelpMessage}. The
- * information for each option consists of the option's name(s), it's required
- * value(s), and an application-supplied description. Value information is
- * generated automaticlly from the conversion code, range, and multiplier
- * specifications (although this can be overriden, as <a
- * href=#valueInfo>described below</a>). The application-supplied description is
- * whatever appears in the specification string after the optional
- * <code>#</code> character. The string returned by {@link #getHelpMessage
- * getHelpMessage} for the <a href=#example>first example above</a> would be
+ * queried by the application using {@link #getHelpMessage getHelpMessage}.
+ * The information for each option consists of the option's name(s), it's
+ * required value(s), and an application-supplied description. Value
+ * information is generated automaticlly from the conversion code, range, and
+ * multiplier specifications (although this can be overriden, as
+ * <a href=#valueInfo>described below</a>).
+ * The application-supplied description is whatever
+ * appears in the specification string after the optional <code>#</code>
+ * character. The string returned by {@link #getHelpMessage getHelpMessage} for
+ * the <a href=#example>first example above</a> would be
*
* <pre>
* Usage: java argparser.SimpleExample
@@ -302,47 +291,48 @@ import java.util.Vector;
*
* The options <code>-help</code> and <code>-?</code> are including in the
* parser by default as help options, and they automatically cause the help
- * message to be printed. To exclude these options, one should use the
- * constructor {@link #ArgParser(String,boolean) ArgParser(synopsis,false)}.
- * Help options can also be specified by the application using
- * {@link #addOption addOption} and the conversion code <code>%h</code>. Help
- * options can be disabled using {@link #setHelpOptionsEnabled
+ * message to be printed. To exclude these
+ * options, one should use the constructor {@link #ArgParser(String,boolean)
+ * ArgParser(synopsis,false)}.
+ * Help options can also be specified by the application using {@link
+ * #addOption addOption} and the conversion code <code>%h</code>. Help options
+ * can be disabled using {@link #setHelpOptionsEnabled
* setHelpOptionsEnabled(false)}.
- *
- * <p>
- * <a name=valueInfo> A description of the required values for an option can be
- * specified explicitly by placing a second <code>#</code> character in the
- * specification string. Everything between the first and second <code>#</code>
- * characters then becomes the value description, and everything after the
- * second <code>#</code> character becomes the option description. For example,
- * if the <code>-theta</code> option above was specified with
- *
+ *
+ * <p><a name=valueInfo>
+ * A description of the required values for an option can be
+ * specified explicitly
+ * by placing a second <code>#</code> character in the specification
+ * string. Everything between the first and second <code>#</code>
+ * characters then becomes the value description, and everything
+ * after the second <code>#</code> character becomes the option
+ * description.
+ * For example, if the <code>-theta</code> option
+ * above was specified with
* <pre>
- * parser.addOption(&quot;-theta %f #NUMBER#theta value (in degrees)&quot;, theta);
+ * parser.addOption ("-theta %f #NUMBER#theta value (in degrees)",theta);
* </pre>
- *
* instead of
- *
* <pre>
- * parser.addOption(&quot;-theta %f #theta value (in degrees)&quot;, theta);
+ * parser.addOption ("-theta %f #theta value (in degrees)", theta);
* </pre>
- *
- * then the corresponding entry in the help message would look like
- *
+ * then the corresponding entry in the help message would look
+ * like
* <pre>
* -theta NUMBER theta value (in degrees)
* </pre>
- *
+ *
* <h3><a name="customArgParsing">Custom Argument Parsing</a></h3>
*
- * An application may find it necessary to handle arguments that don't fit into
- * the framework of this class. There are a couple of ways to do this.
- *
+ * An application may find it necessary to handle arguments that
+ * don't fit into the framework of this class. There are a couple
+ * of ways to do this.
+ *
* <p>
* First, the method {@link #matchAllArgs(String[],int,int)
- * matchAllArgs(args,idx,exitFlags)} returns an array of all unmatched
- * arguments, which can then be handled specially:
- *
+ * matchAllArgs(args,idx,exitFlags)} returns an array of
+ * all unmatched arguments, which can then be handled
+ * specially:
* <pre>
* String[] unmatched =
* parser.matchAllArgs (args, 0, parser.EXIT_ON_ERROR);
@@ -352,13 +342,12 @@ import java.util.Vector;
* </pre>
*
* For instance, this would be useful for an applicatoon that accepts an
- * arbitrary number of input file names. The options can be parsed using
- * <code>matchAllArgs</code>, and the remaining unmatched arguments give the
- * file names.
- *
- * <p>
- * If we need more control over the parsing, we can parse arguments one at a
- * time using {@link #matchArg matchArg}:
+ * arbitrary number of input file names. The options can be parsed using
+ * <code>matchAllArgs</code>, and the remaining unmatched arguments
+ * give the file names.
+ *
+ * <p> If we need more control over the parsing, we can parse arguments one at
+ * a time using {@link #matchArg matchArg}:
*
* <pre>
* int idx = 0;
@@ -376,1793 +365,1936 @@ import java.util.Vector;
* }
* }
* </pre>
- *
+ *
* {@link #matchArg matchArg(args,idx)} matches one option at location
* <code>idx</code> in the argument list, and then returns the location value
- * that should be used for the next match. If an argument does not match any
- * option, {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy
- * of the unmatched argument.
- *
+ * that should be used for the next match. If an argument does
+ * not match any option,
+ * {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy of the
+ * unmatched argument.
+ *
* <h3><a name="argsFromAFile">Reading Arguments From a File</a></h3>
- *
- * The method {@link #prependArgs prependArgs} can be used to automatically read
- * in a set of arguments from a file and prepend them onto an existing argument
- * list. Argument words correspond to white-space-delimited strings, and the
- * file may contain the comment character <code>#</code> (which comments out
- * everything to the end of the current line). A typical usage looks like this:
- *
+ *
+ * The method {@link #prependArgs prependArgs} can be used to automatically
+ * read in a set of arguments from a file and prepend them onto an existing
+ * argument list. Argument words correspond to white-space-delimited strings,
+ * and the file may contain the comment character <code>#</code> (which
+ * comments out everything to the end of the current line). A typical usage
+ * looks like this:
+ *
* <pre>
* ... create parser and add options ...
*
* args = parser.prependArgs (new File(".configFile"), args);
- *
+ *
* parser.matchAllArgs (args);
* </pre>
- *
- * This makes it easy to generate simple configuration files for an application.
- *
+ *
+ * This makes it easy to generate simple configuration files for an
+ * application.
+ *
* @author John E. Lloyd, Fall 2004
*/
-public class ArgParser {
- Vector<Record> matchList;
- // int tabSpacing = 8;
- String synopsisString;
- boolean helpOptionsEnabled = true;
- Record defaultHelpOption = null;
- Record firstHelpOption = null;
- PrintStream printStream = System.out;
- int helpIndent = 24;
- String errMsg = null;
- String unmatchedArg = null;
-
- static String validConversionCodes = "iodxcbfsvh";
-
- /**
- * Indicates that the program should exit with an appropriate message in the
- * event of an erroneous or malformed argument.
- */
- public static int EXIT_ON_ERROR = 1;
-
- /**
- * Indicates that the program should exit with an appropriate message in the
- * event of an unmatched argument.
- */
- public static int EXIT_ON_UNMATCHED = 2;
-
- /**
- * Returns a string containing the valid conversion codes. These are the
- * characters which may follow the <code>%</code> character in the
- * specification string of {@link #addOption addOption}.
- *
- * @return Valid conversion codes
- * @see #addOption
- */
- public static String getValidConversionCodes() {
- return validConversionCodes;
- }
-
- static class NameDesc {
- String name;
- // oneWord implies that any value associated with
- // option is concatenated onto the argument string itself
- boolean oneWord;
- NameDesc next = null;
- }
-
- static class RangePnt {
- double dval = 0;
- long lval = 0;
- String sval = null;
- boolean bval = true;
- boolean closed = true;
-
- RangePnt(String s, boolean closed) {
- sval = s;
- this.closed = closed;
- }
-
- RangePnt(double d, boolean closed) {
- dval = d;
- this.closed = closed;
- }
-
- RangePnt(long l, boolean closed) {
- lval = l;
- this.closed = closed;
- }
-
- RangePnt(boolean b, boolean closed) {
- bval = b;
- this.closed = closed;
- }
-
- RangePnt(StringScanner scanner, int type)
- throws IllegalArgumentException {
- String typeName = null;
- try {
- switch (type) {
- case Record.CHAR: {
- typeName = "character";
- lval = scanner.scanChar();
- break;
- }
- case Record.INT:
- case Record.LONG: {
- typeName = "integer";
- lval = scanner.scanInt();
- break;
- }
- case Record.FLOAT:
- case Record.DOUBLE: {
- typeName = "float";
- dval = scanner.scanDouble();
- break;
- }
- case Record.STRING: {
- typeName = "string";
- sval = scanner.scanString();
- break;
- }
- case Record.BOOLEAN: {
- typeName = "boolean";
- bval = scanner.scanBoolean();
- break;
- }
- }
- } catch (StringScanException e) {
- throw new IllegalArgumentException("Malformed "
- + typeName
- + " '"
- + scanner.substring(scanner.getIndex(),
- e.getFailIndex() + 1) + "' in range spec");
- }
- // this.closed = closed;
- }
-
- void setClosed(boolean closed) {
- this.closed = closed;
- }
-
- boolean getClosed() {
- return closed;
- }
-
- int compareTo(double d) {
- if (dval < d) {
- return -1;
- } else if (d == dval) {
- return 0;
- } else {
- return 1;
- }
- }
-
- int compareTo(long l) {
- if (lval < l) {
- return -1;
- } else if (l == lval) {
- return 0;
- } else {
- return 1;
- }
- }
-
- int compareTo(String s) {
- return sval.compareTo(s);
- }
-
- int compareTo(boolean b) {
- if (b == bval) {
- return 0;
- } else {
- return 1;
- }
- }
-
- public String toString() {
- return "{ dval=" + dval + ", lval=" + lval + ", sval=" + sval
- + ", bval=" + bval + ", closed=" + closed + "}";
- }
- }
-
- class RangeAtom {
- RangePnt low = null;
- RangePnt high = null;
- RangeAtom next = null;
-
- RangeAtom(RangePnt p0, RangePnt p1, int type)
- throws IllegalArgumentException {
- int cmp = 0;
- switch (type) {
- case Record.CHAR:
- case Record.INT:
- case Record.LONG: {
- cmp = p0.compareTo(p1.lval);
- break;
- }
- case Record.FLOAT:
- case Record.DOUBLE: {
- cmp = p0.compareTo(p1.dval);
- break;
- }
- case Record.STRING: {
- cmp = p0.compareTo(p1.sval);
- break;
- }
- }
- if (cmp > 0) { // then switch high and low
- low = p1;
- high = p0;
- } else {
- low = p0;
- high = p1;
- }
- }
-
- RangeAtom(RangePnt p0) throws IllegalArgumentException {
- low = p0;
- }
-
- boolean match(double d) {
- int lc = low.compareTo(d);
- if (high != null) {
- int hc = high.compareTo(d);
- return (lc * hc < 0 || (low.closed && lc == 0) || (high.closed && hc == 0));
- } else {
- return lc == 0;
- }
- }
-
- boolean match(long l) {
- int lc = low.compareTo(l);
- if (high != null) {
- int hc = high.compareTo(l);
- return (lc * hc < 0 || (low.closed && lc == 0) || (high.closed && hc == 0));
- } else {
- return lc == 0;
- }
- }
-
- boolean match(String s) {
- int lc = low.compareTo(s);
- if (high != null) {
- int hc = high.compareTo(s);
- return (lc * hc < 0 || (low.closed && lc == 0) || (high.closed && hc == 0));
- } else {
- return lc == 0;
- }
- }
-
- boolean match(boolean b) {
- return low.compareTo(b) == 0;
- }
-
- public String toString() {
- return "low=" + (low == null ? "null" : low.toString()) + ", high="
- + (high == null ? "null" : high.toString());
- }
- }
-
- class Record {
- NameDesc nameList;
- static final int NOTYPE = 0;
- static final int BOOLEAN = 1;
- static final int CHAR = 2;
- static final int INT = 3;
- static final int LONG = 4;
- static final int FLOAT = 5;
- static final int DOUBLE = 6;
- static final int STRING = 7;
- int type;
- int numValues;
- boolean vectorResult = false;
- boolean required = true;
-
- String helpMsg = null;
- String valueDesc = null;
- String rangeDesc = null;
- Object resHolder = null;
- RangeAtom rangeList = null;
- RangeAtom rangeTail = null;
- char convertCode;
- boolean vval = true; // default value for now
-
- NameDesc firstNameDesc() {
- return nameList;
- }
-
- RangeAtom firstRangeAtom() {
- return rangeList;
- }
-
- int numRangeAtoms() {
- int cnt = 0;
- for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
- cnt++;
- }
- return cnt;
- }
-
- void addRangeAtom(RangeAtom ra) {
- if (rangeList == null) {
- rangeList = ra;
- } else {
- rangeTail.next = ra;
- }
- rangeTail = ra;
- }
-
- boolean withinRange(double d) {
- if (rangeList == null) {
- return true;
- }
- for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
- if (ra.match(d)) {
- return true;
+public class ArgParser
+{
+ Vector<Record> matchList;
+// int tabSpacing = 8;
+ String synopsisString;
+ boolean helpOptionsEnabled = true;
+ Record defaultHelpOption = null;
+ Record firstHelpOption = null;
+ PrintStream printStream = System.out;
+ int helpIndent = 24;
+ String errMsg = null;
+ String unmatchedArg = null;
+
+ static String validConversionCodes = "iodxcbfsvh";
+
+ /**
+ * Indicates that the program should exit with an appropriate message
+ * in the event of an erroneous or malformed argument.*/
+ public static int EXIT_ON_ERROR = 1;
+
+ /**
+ * Indicates that the program should exit with an appropriate message
+ * in the event of an unmatched argument.*/
+ public static int EXIT_ON_UNMATCHED = 2;
+
+ /**
+ * Returns a string containing the valid conversion codes. These
+ * are the characters which may follow the <code>%</code> character in
+ * the specification string of {@link #addOption addOption}.
+ *
+ * @return Valid conversion codes
+ * @see #addOption
+ */
+ public static String getValidConversionCodes()
+ {
+ return validConversionCodes;
+ }
+
+ static class NameDesc
+ {
+ String name;
+ // oneWord implies that any value associated with
+ // option is concatenated onto the argument string itself
+ boolean oneWord;
+ NameDesc next = null;
+ }
+
+ static class RangePnt
+ {
+ double dval = 0;
+ long lval = 0;
+ String sval = null;
+ boolean bval = true;
+ boolean closed = true;
+
+ RangePnt (String s, boolean closed)
+ { sval = s;
+ this.closed = closed;
+ }
+
+ RangePnt (double d, boolean closed)
+ { dval = d;
+ this.closed = closed;
+ }
+
+ RangePnt (long l, boolean closed)
+ { lval = l;
+ this.closed = closed;
+ }
+
+ RangePnt (boolean b, boolean closed)
+ { bval = b;
+ this.closed = closed;
+ }
+
+ RangePnt (StringScanner scanner, int type)
+ throws IllegalArgumentException
+ {
+ String typeName = null;
+ try
+ { switch (type)
+ {
+ case Record.CHAR:
+ { typeName = "character";
+ lval = scanner.scanChar();
+ break;
+ }
+ case Record.INT:
+ case Record.LONG:
+ { typeName = "integer";
+ lval = scanner.scanInt();
+ break;
+ }
+ case Record.FLOAT:
+ case Record.DOUBLE:
+ { typeName = "float";
+ dval = scanner.scanDouble();
+ break;
+ }
+ case Record.STRING:
+ { typeName = "string";
+ sval = scanner.scanString();
+ break;
+ }
+ case Record.BOOLEAN:
+ { typeName = "boolean";
+ bval = scanner.scanBoolean();
+ break;
+ }
+ }
+ }
+ catch (StringScanException e)
+ { throw new IllegalArgumentException (
+ "Malformed " + typeName + " '" +
+ scanner.substring(scanner.getIndex(),
+ e.getFailIndex()+1) +
+ "' in range spec");
+ }
+// this.closed = closed;
+ }
+
+ void setClosed (boolean closed)
+ { this.closed = closed;
+ }
+
+ boolean getClosed()
+ { return closed;
+ }
+
+ int compareTo (double d)
+ { if (dval < d)
+ { return -1;
+ }
+ else if (d == dval)
+ { return 0;
+ }
+ else
+ { return 1;
+ }
+ }
+
+ int compareTo (long l)
+ { if (lval < l)
+ { return -1;
+ }
+ else if (l == lval)
+ { return 0;
+ }
+ else
+ { return 1;
+ }
+ }
+
+ int compareTo (String s)
+ { return sval.compareTo (s);
+ }
+
+ int compareTo (boolean b)
+ { if (b == bval)
+ { return 0;
+ }
+ else
+ { return 1;
+ }
+ }
+
+ public String toString()
+ { return "{ dval=" + dval + ", lval=" + lval +
+ ", sval=" + sval + ", bval=" + bval +
+ ", closed=" + closed + "}";
+ }
+ }
+
+ class RangeAtom
+ {
+ RangePnt low = null;
+ RangePnt high = null;
+ RangeAtom next = null;
+
+ RangeAtom (RangePnt p0, RangePnt p1, int type)
+ throws IllegalArgumentException
+ {
+ int cmp = 0;
+ switch (type)
+ {
+ case Record.CHAR:
+ case Record.INT:
+ case Record.LONG:
+ { cmp = p0.compareTo (p1.lval);
+ break;
+ }
+ case Record.FLOAT:
+ case Record.DOUBLE:
+ { cmp = p0.compareTo (p1.dval);
+ break;
+ }
+ case Record.STRING:
+ { cmp = p0.compareTo (p1.sval);
+ break;
+ }
+ }
+ if (cmp > 0)
+ { // then switch high and low
+ low = p1;
+ high = p0;
+ }
+ else
+ { low = p0;
+ high = p1;
+ }
+ }
+
+ RangeAtom (RangePnt p0)
+ throws IllegalArgumentException
+ {
+ low = p0;
+ }
+
+ boolean match (double d)
+ { int lc = low.compareTo(d);
+ if (high != null)
+ { int hc = high.compareTo(d);
+ return (lc*hc < 0 ||
+ (low.closed && lc==0) ||
+ (high.closed && hc==0));
+ }
+ else
+ { return lc == 0;
+ }
+ }
+
+ boolean match (long l)
+ { int lc = low.compareTo(l);
+ if (high != null)
+ { int hc = high.compareTo(l);
+ return (lc*hc < 0 ||
+ (low.closed && lc==0) ||
+ (high.closed && hc==0));
+ }
+ else
+ { return lc == 0;
+ }
+ }
+
+ boolean match (String s)
+ { int lc = low.compareTo(s);
+ if (high != null)
+ { int hc = high.compareTo(s);
+ return (lc*hc < 0 ||
+ (low.closed && lc==0) ||
+ (high.closed && hc==0));
+ }
+ else
+ { return lc == 0;
+ }
+ }
+
+ boolean match (boolean b)
+ { return low.compareTo(b) == 0;
+ }
+
+ public String toString()
+ { return "low=" + (low==null ? "null" : low.toString()) +
+ ", high=" + (high==null ? "null" : high.toString());
+ }
+ }
+
+ class Record
+ {
+ NameDesc nameList;
+ static final int NOTYPE = 0;
+ static final int BOOLEAN = 1;
+ static final int CHAR = 2;
+ static final int INT = 3;
+ static final int LONG = 4;
+ static final int FLOAT = 5;
+ static final int DOUBLE = 6;
+ static final int STRING = 7;
+ int type;
+ int numValues;
+ boolean vectorResult = false;
+ boolean required = true;
+
+ String helpMsg = null;
+ String valueDesc = null;
+ String rangeDesc = null;
+ Object resHolder = null;
+ RangeAtom rangeList = null;
+ RangeAtom rangeTail = null;
+ char convertCode;
+ boolean vval = true; // default value for now
+
+ NameDesc firstNameDesc()
+ {
+ return nameList;
+ }
+
+ RangeAtom firstRangeAtom()
+ {
+ return rangeList;
+ }
+
+ int numRangeAtoms()
+ { int cnt = 0;
+ for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
+ { cnt++;
+ }
+ return cnt;
+ }
+
+ void addRangeAtom (RangeAtom ra)
+ { if (rangeList == null)
+ { rangeList = ra;
+ }
+ else
+ { rangeTail.next = ra;
+ }
+ rangeTail = ra;
+ }
+
+ boolean withinRange (double d)
+ {
+ if (rangeList == null)
+ { return true;
+ }
+ for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
+ { if (ra.match (d))
+ { return true;
+ }
+ }
+ return false;
+ }
+
+ boolean withinRange (long l)
+ {
+ if (rangeList == null)
+ { return true;
+ }
+ for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
+ { if (ra.match (l))
+ { return true;
+ }
+ }
+ return false;
+ }
+
+ boolean withinRange (String s)
+ {
+ if (rangeList == null)
+ { return true;
+ }
+ for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
+ { if (ra.match (s))
+ { return true;
+ }
+ }
+ return false;
+ }
+
+ boolean withinRange (boolean b)
+ {
+ if (rangeList == null)
+ { return true;
+ }
+ for (RangeAtom ra=rangeList; ra!=null; ra=ra.next)
+ { if (ra.match (b))
+ { return true;
+ }
+ }
+ return false;
+ }
+
+ String valTypeName()
+ {
+ switch (convertCode)
+ {
+ case 'i':
+ { return ("integer");
+ }
+ case 'o':
+ { return ("octal integer");
+ }
+ case 'd':
+ { return ("decimal integer");
+ }
+ case 'x':
+ { return ("hex integer");
+ }
+ case 'c':
+ { return ("char");
+ }
+ case 'b':
+ { return ("boolean");
+ }
+ case 'f':
+ { return ("float");
+ }
+ case 's':
+ { return ("string");
+ }
+ }
+ return ("unknown");
+ }
+
+ void scanValue (Object result, String name, String s, int resultIdx)
+ throws ArgParseException
+ {
+ double dval = 0;
+ String sval = null;
+ long lval = 0;
+ boolean bval = false;
+
+ if (s.length()==0)
+ { throw new ArgParseException
+ (name, "requires a contiguous value");
+ }
+ StringScanner scanner = new StringScanner(s);
+ try
+ {
+ switch (convertCode)
+ {
+ case 'i':
+ { lval = scanner.scanInt();
+ break;
+ }
+ case 'o':
+ { lval = scanner.scanInt (8, false);
+ break;
+ }
+ case 'd':
+ { lval = scanner.scanInt (10, false);
+ break;
+ }
+ case 'x':
+ { lval = scanner.scanInt (16, false);
+ break;
+ }
+ case 'c':
+ { lval = scanner.scanChar();
+ break;
+ }
+ case 'b':
+ { bval = scanner.scanBoolean();
+ break;
+ }
+ case 'f':
+ { dval = scanner.scanDouble();
+ break;
+ }
+ case 's':
+ { sval = scanner.getString();
+ break;
+ }
+ }
+ }
+ catch (StringScanException e)
+ { throw new ArgParseException (
+ name, "malformed " + valTypeName() + " '" + s + "'");
+ }
+ scanner.skipWhiteSpace();
+ if (!scanner.atEnd())
+ { throw new ArgParseException (
+ name, "malformed " + valTypeName() + " '" + s + "'");
+ }
+ boolean outOfRange = false;
+ switch (type)
+ {
+ case CHAR:
+ case INT:
+ case LONG:
+ { outOfRange = !withinRange (lval);
+ break;
+ }
+ case FLOAT:
+ case DOUBLE:
+ { outOfRange = !withinRange (dval);
+ break;
+ }
+ case STRING:
+ { outOfRange = !withinRange (sval);
+ break;
+ }
+ case BOOLEAN:
+ { outOfRange = !withinRange (bval);
+ break;
+ }
+ }
+ if (outOfRange)
+ { String errmsg = "value " + s + " not in range ";
+ throw new ArgParseException (
+ name, "value '" + s + "' not in range " + rangeDesc);
+ }
+ if (result.getClass().isArray())
+ {
+ switch (type)
+ {
+ case BOOLEAN:
+ { ((boolean[])result)[resultIdx] = bval;
+ break;
+ }
+ case CHAR:
+ { ((char[])result)[resultIdx] = (char)lval;
+ break;
+ }
+ case INT:
+ { ((int[])result)[resultIdx] = (int)lval;
+ break;
+ }
+ case LONG:
+ { ((long[])result)[resultIdx] = lval;
+ break;
+ }
+ case FLOAT:
+ { ((float[])result)[resultIdx] = (float)dval;
+ break;
+ }
+ case DOUBLE:
+ { ((double[])result)[resultIdx] = dval;
+ break;
+ }
+ case STRING:
+ { ((String[])result)[resultIdx] = sval;
+ break;
+ }
+ }
+ }
+ else
+ {
+ switch (type)
+ {
+ case BOOLEAN:
+ { ((BooleanHolder)result).value = bval;
+ break;
+ }
+ case CHAR:
+ { ((CharHolder)result).value = (char)lval;
+ break;
+ }
+ case INT:
+ { ((IntHolder)result).value = (int)lval;
+ break;
+ }
+ case LONG:
+ { ((LongHolder)result).value = lval;
+ break;
+ }
+ case FLOAT:
+ { ((FloatHolder)result).value = (float)dval;
+ break;
+ }
+ case DOUBLE:
+ { ((DoubleHolder)result).value = dval;
+ break;
+ }
+ case STRING:
+ { ((StringHolder)result).value = sval;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ private String firstHelpOptionName()
+ {
+ if (firstHelpOption != null)
+ { return firstHelpOption.nameList.name;
+ }
+ else
+ { return null;
+ }
+ }
+
+ /**
+ * Creates an <code>ArgParser</code> with a synopsis
+ * string, and the default help options <code>-help</code> and
+ * <code>-&#063;</code>.
+ *
+ * @param synopsisString string that briefly describes program usage,
+ * for use by {@link #getHelpMessage getHelpMessage}.
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public ArgParser(String synopsisString)
+ {
+ this (synopsisString, true);
+ }
+
+ /**
+ * Creates an <code>ArgParser</code> with a synopsis
+ * string. The help options <code>-help</code> and
+ * <code>-?</code> are added if <code>defaultHelp</code>
+ * is true.
+ *
+ * @param synopsisString string that briefly describes program usage,
+ * for use by {@link #getHelpMessage getHelpMessage}.
+ * @param defaultHelp if true, adds the default help options
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public ArgParser(String synopsisString, boolean defaultHelp)
+ {
+ matchList = new Vector<Record>(128);
+ this.synopsisString = synopsisString;
+ if (defaultHelp)
+ { addOption ("-help,-? %h #displays help information", null);
+ defaultHelpOption = firstHelpOption = matchList.get(0);
+ }
+ }
+
+ /**
+ * Returns the synopsis string used by the parser.
+ * The synopsis string is a short description of how to invoke
+ * the program, and usually looks something like
+ * <p>
+ * <prec>
+ * "java somepackage.SomeClass [options] files ..."
+ * </prec>
+ *
+ * <p> It is used in help and error messages.
+ *
+ * @return synopsis string
+ * @see ArgParser#setSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public String getSynopsisString ()
+ {
+ return synopsisString;
+ }
+
+ /**
+ * Sets the synopsis string used by the parser.
+ *
+ * @param s new synopsis string
+ * @see ArgParser#getSynopsisString
+ * @see ArgParser#getHelpMessage
+ */
+ public void setSynopsisString (String s)
+ {
+ synopsisString = s;
+ }
+
+ /**
+ * Indicates whether or not help options are enabled.
+ *
+ * @return true if help options are enabled
+ * @see ArgParser#setHelpOptionsEnabled
+ * @see ArgParser#addOption
+ */
+ public boolean getHelpOptionsEnabled ()
+ {
+ return helpOptionsEnabled;
+ }
+
+ /**
+ * Enables or disables help options. Help options are those
+ * associated with a conversion code of <code>%h</code>. If
+ * help options are enabled, and a help option is matched,
+ * then the string produced by
+ * {@link #getHelpMessage getHelpMessage}
+ * is printed to the default print stream and the program
+ * exits with code 0. Otherwise, arguments which match help
+ * options are ignored.
+ *
+ * @param enable enables help options if <code>true</code>.
+ * @see ArgParser#getHelpOptionsEnabled
+ * @see ArgParser#addOption
+ * @see ArgParser#setDefaultPrintStream */
+ public void setHelpOptionsEnabled(boolean enable)
+ { helpOptionsEnabled = enable;
+ }
+
+ /**
+ * Returns the default print stream used for outputting help
+ * and error information.
+ *
+ * @return default print stream
+ * @see ArgParser#setDefaultPrintStream
+ */
+ public PrintStream getDefaultPrintStream()
+ { return printStream;
+ }
+
+ /**
+ * Sets the default print stream used for outputting help
+ * and error information.
+ *
+ * @param stream new default print stream
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public void setDefaultPrintStream (PrintStream stream)
+ {
+ printStream = stream;
+ }
+
+ /**
+ * Gets the indentation used by {@link #getHelpMessage
+ * getHelpMessage}.
+ *
+ * @return number of indentation columns
+ * @see ArgParser#setHelpIndentation
+ * @see ArgParser#getHelpMessage
+ */
+ public int getHelpIndentation()
+ {
+ return helpIndent;
+ }
+
+ /**
+ * Sets the indentation used by {@link #getHelpMessage
+ * getHelpMessage}. This is the number of columns that an option's help
+ * information is indented. If the option's name and value information
+ * can fit within this number of columns, then all information about
+ * the option is placed on one line. Otherwise, the indented help
+ * information is placed on a separate line.
+ *
+ * @param indent number of indentation columns
+ * @see ArgParser#getHelpIndentation
+ * @see ArgParser#getHelpMessage
+ */
+ public void setHelpIndentation (int indent)
+ { helpIndent = indent;
+ }
+
+// public void setTabSpacing (int n)
+// { tabSpacing = n;
+// }
+
+// public int getTabSpacing ()
+// { return tabSpacing;
+// }
+
+ private void scanRangeSpec (Record rec, String s)
+ throws IllegalArgumentException
+ {
+ StringScanner scanner = new StringScanner (s);
+ int i0, i = 1;
+ char c, c0, c1;
+
+ scanner.setStringDelimiters (")],}");
+ c = scanner.getc(); // swallow the first '{'
+ scanner.skipWhiteSpace();
+ while ((c=scanner.peekc()) != '}')
+ { RangePnt p0, p1;
+
+ if (c == '[' || c == '(')
+ {
+ if (rec.convertCode == 'v' || rec.convertCode == 'b')
+ { throw new IllegalArgumentException
+ ("Sub ranges not supported for %b or %v");
+ }
+ c0 = scanner.getc(); // record & swallow character
+ scanner.skipWhiteSpace();
+ p0 = new RangePnt (scanner, rec.type);
+ scanner.skipWhiteSpace();
+ if (scanner.getc() != ',')
+ { throw new IllegalArgumentException
+ ("Missing ',' in subrange specification");
+ }
+ p1 = new RangePnt (scanner, rec.type);
+ scanner.skipWhiteSpace();
+ if ((c1=scanner.getc()) != ']' && c1 != ')')
+ { throw new IllegalArgumentException
+ ("Unterminated subrange");
+ }
+ if (c0 == '(')
+ { p0.setClosed (false);
+ }
+ if (c1 == ')')
+ { p1.setClosed (false);
+ }
+ rec.addRangeAtom (new RangeAtom (p0, p1, rec.type));
+ }
+ else
+ { scanner.skipWhiteSpace();
+ p0 = new RangePnt (scanner, rec.type);
+ rec.addRangeAtom (new RangeAtom (p0));
+ }
+ scanner.skipWhiteSpace();
+ if ((c=scanner.peekc()) == ',')
+ { scanner.getc();
+ scanner.skipWhiteSpace();
+ }
+ else if (c != '}')
+ {
+ throw new IllegalArgumentException
+ ("Range spec: ',' or '}' expected");
+ }
+ }
+ if (rec.numRangeAtoms()==1)
+ { rec.rangeDesc = s.substring (1, s.length()-1);
+ }
+ else
+ { rec.rangeDesc = s;
+ }
+ }
+
+ private int defaultResultType (char convertCode)
+ {
+ switch (convertCode)
+ {
+ case 'i':
+ case 'o':
+ case 'd':
+ case 'x':
+ { return Record.LONG;
+ }
+ case 'c':
+ { return Record.CHAR;
+ }
+ case 'v':
+ case 'b':
+ { return Record.BOOLEAN;
+ }
+ case 'f':
+ { return Record.DOUBLE;
+ }
+ case 's':
+ { return Record.STRING;
+ }
+ }
+ return Record.NOTYPE;
+ }
+
+ /**
+ * Adds a new option description to the parser. The method takes two
+ * arguments: a specification string, and a result holder in which to
+ * store the associated value.
+ *
+ * <p>The specification string has the general form
+ *
+ * <p> <var>optionNames</var>
+ * <code>%</code><var>conversionCode</var>
+ * [<code>{</code><var>rangeSpec</var><code>}</code>]
+ * [<code>X</code><var>multiplier</var>]
+ * [<code>#</code><var>valueDescription</var>]
+ * [<code>#</code><var>optionDescription</var>] </code>
+ *
+ * <p>
+ * where
+ * <ul> <p><li><var>optionNames</var> is a
+ * comma-separated list of names for the option
+ * (such as <code>-f, --file</code>).
+ *
+ * <p><li><var>conversionCode</var> is a single letter,
+ * following a <code>%</code> character, specifying
+ * information about what value the option requires:
+ *
+ * <table>
+ * <tr><td><code>%f</code></td><td>a floating point number</td>
+ * <tr><td><code>%i</code></td><td>an integer, in either decimal,
+ * hex (if preceeded by <code>0x</code>), or
+ * octal (if preceeded by <code>0</code>)</td>
+ * <tr valign=top>
+ * <td><code>%d</code></td><td>a decimal integer</td>
+ * <tr valign=top>
+ * <td><code>%o</code></td><td>an octal integer</td>
+ * <tr valign=top>
+ * <td><code>%h</code></td><td>a hex integer (without the
+ * preceeding <code>0x</code>)</td>
+ * <tr valign=top>
+ * <td><code>%c</code></td><td>a single character, including
+ * escape sequences (such as <code>\n</code> or <code>\007</code>),
+ * and optionally enclosed in single quotes
+ * <tr valign=top>
+ * <td><code>%b</code></td><td>a boolean value (<code>true</code>
+ * or <code>false</code>)</td>
+ * <tr valign=top>
+ * <td><code>%s</code></td><td>a string. This will
+ * be the argument string itself (or its remainder, in
+ * the case of a single word option)</td>
+ * <tr valign=top>
+ * <td><code>%v</code></td><td>no explicit value is expected,
+ * but a boolean value of <code>true</code> (by default)
+ * will be stored into the associated result holder if this
+ * option is matched. If one wishes to have a value of
+ * <code>false</code> stored instead, then the <code>%v</code>
+ * should be followed by a "range spec" containing
+ * <code>false</code>, as in <code>%v{false}</code>.
+ * </table>
+ *
+ * <p><li><var>rangeSpec</var> is an optional range specification,
+ * placed inside curly braces, consisting of a
+ * comma-separated list of range items each specifying
+ * permissible values for the option. A range item may be an
+ * individual value, or it may itself be a subrange,
+ * consisting of two individual values, separated by a comma,
+ * and enclosed in square or round brackets. Square and round
+ * brackets denote closed and open endpoints of a subrange, indicating
+ * that the associated endpoint value is included or excluded
+ * from the subrange.
+ * The values specified in the range spec need to be
+ * consistent with the type of value expected by the option.
+ *
+ * <p><b>Examples:</b>
+ *
+ * <p>A range spec of <code>{2,4,8,16}</code> for an integer
+ * value will allow the integers 2, 4, 8, or 16.
+ *
+ * <p>A range spec of <code>{[-1.0,1.0]}</code> for a floating
+ * point value will allow any floating point number in the
+ * range -1.0 to 1.0.
+ *
+ * <p>A range spec of <code>{(-88,100],1000}</code> for an integer
+ * value will allow values > -88 and <= 100, as well as 1000.
+ *
+ * <p>A range spec of <code>{"foo", "bar", ["aaa","zzz")} </code> for a
+ * string value will allow strings equal to <code>"foo"</code> or
+ * <code>"bar"</code>, plus any string lexically greater than or equal
+ * to <code>"aaa"</code> but less then <code>"zzz"</code>.
+ *
+ * <p><li><var>multiplier</var> is an optional integer,
+ * following a <code>X</code> character,
+ * indicating the number of values which the option expects.
+ * If the multiplier is not specified, it is assumed to be
+ * 1. If the multiplier value is greater than 1, then the
+ * result holder should be either an array (of appropriate
+ * type) with a length greater than or equal to the multiplier
+ * value, or a <code>java.util.Vector</code>
+ * <a href=#vectorHolder>as discussed below</a>.
+ *
+ * <p><li><var>valueDescription</var> is an optional
+ * description of the option's value requirements,
+ * and consists of all
+ * characters between two <code>#</code> characters.
+ * The final <code>#</code> character initiates the
+ * <i>option description</i>, which may be empty.
+ * The value description is used in
+ * <a href=#helpInfo>generating help messages</a>.
+ *
+ * <p><li><var>optionDescription</var> is an optional
+ * description of the option itself, consisting of all
+ * characters between a <code>#</code> character
+ * and the end of the specification string.
+ * The option description is used in
+ * <a href=#helpInfo>generating help messages</a>.
+ * </ul>
+ *
+ * <p>The result holder must be an object capable of holding
+ * a value compatible with the conversion code,
+ * or it must be a <code>java.util.Vector</code>.
+ * When the option is matched, its associated value is
+ * placed in the result holder. If the same option is
+ * matched repeatedly, the result holder value will be overwritten,
+ * unless the result holder is a <code>java.util.Vector</code>,
+ * in which
+ * case new holder objects for each match will be allocated
+ * and added to the vector. Thus if
+ * multiple instances of an option are desired by the
+ * program, the result holder should be a
+ * <code>java.util.Vector</code>.
+ *
+ * <p>If the result holder is not a <code>Vector</code>, then
+ * it must correspond as follows to the conversion code:
+ *
+ * <table>
+ * <tr valign=top>
+ * <td><code>%i</code>, <code>%d</code>, <code>%x</code>,
+ * <code>%o</code></td>
+ * <td>{@link argparser.IntHolder IntHolder},
+ * {@link argparser.LongHolder LongHolder}, <code>int[]</code>, or
+ * <code>long[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%f</code></td>
+ * <td>{@link argparser.FloatHolder FloatHolder},
+ * {@link argparser.DoubleHolder DoubleHolder},
+ * <code>float[]</code>, or
+ * <code>double[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%b</code>, <code>%v</code></td>
+ * <td>{@link argparser.BooleanHolder BooleanHolder} or
+ * <code>boolean[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%s</code></td>
+ * <td>{@link argparser.StringHolder StringHolder} or
+ * <code>String[]</code></td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%c</code></td>
+ * <td>{@link argparser.CharHolder CharHolder} or
+ * <code>char[]</code></td>
+ * </tr>
+ * </table>
+ *
+ * <p>In addition, if the multiplier is greater than 1,
+ * then only the array type indicated above may be used,
+ * and the array must be at least as long as the multiplier.
+ *
+ * <p><a name=vectorHolder>If the result holder is a
+ * <code>Vector</code>, then the system will create an appropriate
+ * result holder object and add it to the vector. Multiple occurances
+ * of the option will cause multiple results to be added to the vector.
+ *
+ * <p>The object allocated by the system to store the result
+ * will correspond to the conversion code as follows:
+ *
+ * <table>
+ * <tr valign=top>
+ * <td><code>%i</code>, <code>%d</code>, <code>%x</code>,
+ * <code>%o</code></td>
+ * <td>{@link argparser.LongHolder LongHolder}, or
+ * <code>long[]</code> if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%f</code></td>
+ * <td>{@link argparser.DoubleHolder DoubleHolder}, or
+ * <code>double[]</code> if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%b</code>, <code>%v</code></td>
+ * <td>{@link argparser.BooleanHolder BooleanHolder}, or
+ * <code>boolean[]</code>
+ * if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%s</code></td>
+ * <td>{@link argparser.StringHolder StringHolder}, or
+ * <code>String[]</code>
+ * if the multiplier value exceeds 1</td>
+ * </tr>
+ *
+ * <tr valign=top>
+ * <td><code>%c</code></td>
+ * <td>{@link argparser.CharHolder CharHolder}, or <code>char[]</code>
+ * if the multiplier value exceeds 1</td>
+ * </tr>
+ * </table>
+ *
+ * @param spec the specification string
+ * @param resHolder object in which to store the associated
+ * value
+ * @throws IllegalArgumentException if there is an error in
+ * the specification or if the result holder is of an invalid
+ * type. */
+ public void addOption (String spec, Object resHolder)
+ throws IllegalArgumentException
+ {
+ // null terminated string is easier to parse
+ StringScanner scanner = new StringScanner(spec);
+ Record rec = null;
+ NameDesc nameTail = null;
+ NameDesc ndesc;
+ int i0, i1;
+ char c;
+
+ do
+ { ndesc = new NameDesc();
+ boolean nameEndsInWhiteSpace = false;
+
+ scanner.skipWhiteSpace();
+ i0 = scanner.getIndex();
+ while (!Character.isWhitespace(c=scanner.getc()) &&
+ c != ',' && c != '%' && c != '\000')
+ ;
+ i1 = scanner.getIndex();
+ if (c!='\000')
+ { i1--;
+ }
+ if (i0==i1)
+ { // then c is one of ',' '%' or '\000'
+ throw new IllegalArgumentException
+ ("Null option name given");
+ }
+ if (Character.isWhitespace(c))
+ { nameEndsInWhiteSpace = true;
+ scanner.skipWhiteSpace();
+ c = scanner.getc();
+ }
+ if (c=='\000')
+ { throw new IllegalArgumentException
+ ("No conversion character given");
+ }
+ if (c != ',' && c != '%')
+ { throw new IllegalArgumentException
+ ("Names not separated by ','");
+ }
+ ndesc.name = scanner.substring (i0, i1);
+ if (rec == null)
+ { rec = new Record();
+ rec.nameList = ndesc;
+ }
+ else
+ { nameTail.next = ndesc;
+ }
+ nameTail = ndesc;
+ ndesc.oneWord = !nameEndsInWhiteSpace;
+ }
+ while (c != '%');
+
+ if (!nameTail.oneWord)
+ { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ { ndesc.oneWord = false;
+ }
+ }
+ c = scanner.getc();
+ if (c=='\000')
+ { throw new IllegalArgumentException
+ ("No conversion character given");
+ }
+ if (validConversionCodes.indexOf(c) == -1)
+ { throw new IllegalArgumentException
+ ("Conversion code '" + c + "' not one of '" +
+ validConversionCodes + "'");
+ }
+ rec.convertCode = c;
+
+ if (resHolder instanceof Vector)
+ { rec.vectorResult = true;
+ rec.type = defaultResultType (rec.convertCode);
+ }
+ else
+ {
+ switch (rec.convertCode)
+ {
+ case 'i':
+ case 'o':
+ case 'd':
+ case 'x':
+ { if (resHolder instanceof LongHolder ||
+ resHolder instanceof long[])
+ { rec.type = Record.LONG;
+ }
+ else if (resHolder instanceof IntHolder ||
+ resHolder instanceof int[])
+ { rec.type = Record.INT;
+ }
+ else
+ { throw new IllegalArgumentException (
+ "Invalid result holder for %" + c);
+ }
+ break;
+ }
+ case 'c':
+ { if (!(resHolder instanceof CharHolder) &&
+ !(resHolder instanceof char[]))
+ { throw new IllegalArgumentException (
+ "Invalid result holder for %c");
+ }
+ rec.type = Record.CHAR;
+ break;
+ }
+ case 'v':
+ case 'b':
+ { if (!(resHolder instanceof BooleanHolder) &&
+ !(resHolder instanceof boolean[]))
+ { throw new IllegalArgumentException (
+ "Invalid result holder for %" + c);
+ }
+ rec.type = Record.BOOLEAN;
+ break;
+ }
+ case 'f':
+ { if (resHolder instanceof DoubleHolder ||
+ resHolder instanceof double[])
+ { rec.type = Record.DOUBLE;
+ }
+ else if (resHolder instanceof FloatHolder ||
+ resHolder instanceof float[])
+ { rec.type = Record.FLOAT;
+ }
+ else
+ { throw new IllegalArgumentException (
+ "Invalid result holder for %f");
+ }
+ break;
+ }
+ case 's':
+ { if (!(resHolder instanceof StringHolder) &&
+ !(resHolder instanceof String[]))
+ { throw new IllegalArgumentException (
+ "Invalid result holder for %s");
+ }
+ rec.type = Record.STRING;
+ break;
+ }
+ case 'h':
+ { // resHolder is ignored for this type
+ break;
+ }
+ }
+ }
+ if (rec.convertCode == 'h')
+ { rec.resHolder = null;
+ }
+ else
+ { rec.resHolder = resHolder;
+ }
+
+ scanner.skipWhiteSpace();
+ // get the range specification, if any
+ if (scanner.peekc() == '{')
+ {
+ if (rec.convertCode == 'h')
+ { throw new IllegalArgumentException
+ ("Ranges not supported for %h");
+ }
+// int bcnt = 0;
+ i0 = scanner.getIndex(); // beginning of range spec
+ do
+ { c = scanner.getc();
+ if (c=='\000')
+ { throw new IllegalArgumentException
+ ("Unterminated range specification");
+ }
+// else if (c=='[' || c=='(')
+// { bcnt++;
+// }
+// else if (c==']' || c==')')
+// { bcnt--;
+// }
+// if ((rec.convertCode=='v'||rec.convertCode=='b') && bcnt>1)
+// { throw new IllegalArgumentException
+// ("Sub ranges not supported for %b or %v");
+// }
+ }
+ while (c != '}');
+// if (c != ']')
+// { throw new IllegalArgumentException
+// ("Range specification must end with ']'");
+// }
+ i1 = scanner.getIndex(); // end of range spec
+ scanRangeSpec (rec, scanner.substring (i0, i1));
+ if (rec.convertCode == 'v' && rec.rangeList!=null)
+ { rec.vval = rec.rangeList.low.bval;
+ }
+ }
+ // check for value multiplicity information, if any
+ if (scanner.peekc() == 'X')
+ {
+ if (rec.convertCode == 'h')
+ { throw new IllegalArgumentException
+ ("Multipliers not supported for %h");
+ }
+ scanner.getc();
+ try
+ { rec.numValues = (int)scanner.scanInt();
+ }
+ catch (StringScanException e)
+ { throw new IllegalArgumentException
+ ("Malformed value multiplier");
+ }
+ if (rec.numValues <= 0)
+ { throw new IllegalArgumentException
+ ("Value multiplier number must be > 0");
+ }
+ }
+ else
+ { rec.numValues = 1;
+ }
+ if (rec.numValues > 1)
+ { for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ { if (ndesc.oneWord)
+ { throw new IllegalArgumentException (
+"Multiplier value incompatible with one word option " + ndesc.name);
+ }
+ }
+ }
+ if (resHolder != null && resHolder.getClass().isArray())
+ { if (Array.getLength(resHolder) < rec.numValues)
+ { throw new IllegalArgumentException (
+"Result holder array must have a length >= " + rec.numValues);
+ }
+ }
+ else
+ { if (rec.numValues > 1 && !(resHolder instanceof Vector))
+ { throw new IllegalArgumentException (
+"Multiplier requires result holder to be an array of length >= "
++ rec.numValues);
+ }
+ }
+
+ // skip white space following conversion information
+ scanner.skipWhiteSpace();
+
+ // get the help message, if any
+
+ if (!scanner.atEnd())
+ { if (scanner.getc() != '#')
+ { throw new IllegalArgumentException
+ ("Illegal character(s), expecting '#'");
+ }
+ String helpInfo = scanner.substring (scanner.getIndex());
+ // look for second '#'. If there is one, then info
+ // between the first and second '#' is the value descriptor.
+ int k = helpInfo.indexOf ("#");
+ if (k != -1)
+ { rec.valueDesc = helpInfo.substring (0, k);
+ rec.helpMsg = helpInfo.substring (k+1);
+ }
+ else
+ { rec.helpMsg = helpInfo;
+ }
+ }
+ else
+ { rec.helpMsg = "";
+ }
+
+ // parse helpMsg for required/optional information if present
+ // default to required
+ if (rec.helpMsg.indexOf("(optional") != -1) {
+ rec.required = false;
+ }
+
+ // add option information to match list
+ if (rec.convertCode == 'h' && firstHelpOption == defaultHelpOption)
+ { matchList.remove (defaultHelpOption);
+ firstHelpOption = rec;
+ }
+ matchList.add (rec);
+ }
+
+ Record lastMatchRecord ()
+ { return (Record)matchList.lastElement();
+ }
+
+ private Record getRecord (String arg, ObjectHolder ndescHolder)
+ {
+ NameDesc ndesc;
+ for (int i=0; i<matchList.size(); i++)
+ { Record rec = (Record)matchList.get(i);
+ for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ { if (rec.convertCode != 'v' && ndesc.oneWord)
+ { if (arg.startsWith (ndesc.name))
+ { if (ndescHolder != null)
+ { ndescHolder.value = ndesc;
+ }
+ return rec;
+ }
+ }
+ else
+ { if (arg.equals (ndesc.name))
+ { if (ndescHolder != null)
+ { ndescHolder.value = ndesc;
+ }
+ return rec;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ public void checkRequiredArgs() {
+ for (int i=1; i<matchList.size(); i++) {
+ Record rec = (Record)matchList.get(i);
+ StringHolder myString = (StringHolder) rec.resHolder;
+ if (((myString.value == null) || (myString.value.equals(""))) && (rec.required)) {
+ printErrorAndExit("Required parameter " + rec.nameList.name + " is not specified.");
}
}
- return false;
- }
-
- boolean withinRange(long l) {
- if (rangeList == null) {
- return true;
- }
- for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
- if (ra.match(l)) {
- return true;
- }
- }
- return false;
- }
-
- boolean withinRange(String s) {
- if (rangeList == null) {
- return true;
- }
- for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
- if (ra.match(s)) {
- return true;
- }
- }
- return false;
- }
-
- boolean withinRange(boolean b) {
- if (rangeList == null) {
- return true;
- }
- for (RangeAtom ra = rangeList; ra != null; ra = ra.next) {
- if (ra.match(b)) {
- return true;
- }
- }
- return false;
- }
-
- String valTypeName() {
- switch (convertCode) {
- case 'i': {
- return ("integer");
- }
- case 'o': {
- return ("octal integer");
- }
- case 'd': {
- return ("decimal integer");
- }
- case 'x': {
- return ("hex integer");
- }
- case 'c': {
- return ("char");
- }
- case 'b': {
- return ("boolean");
- }
- case 'f': {
- return ("float");
- }
- case 's': {
- return ("string");
- }
- }
- return ("unknown");
- }
-
- void scanValue(Object result, String name, String s, int resultIdx)
- throws ArgParseException {
- double dval = 0;
- String sval = null;
- long lval = 0;
- boolean bval = false;
-
- if (s.length() == 0) {
- throw new ArgParseException(name, "requires a contiguous value");
- }
- StringScanner scanner = new StringScanner(s);
- try {
- switch (convertCode) {
- case 'i': {
- lval = scanner.scanInt();
- break;
- }
- case 'o': {
- lval = scanner.scanInt(8, false);
- break;
- }
- case 'd': {
- lval = scanner.scanInt(10, false);
- break;
- }
- case 'x': {
- lval = scanner.scanInt(16, false);
- break;
- }
- case 'c': {
- lval = scanner.scanChar();
- break;
- }
- case 'b': {
- bval = scanner.scanBoolean();
- break;
- }
- case 'f': {
- dval = scanner.scanDouble();
- break;
- }
- case 's': {
- sval = scanner.getString();
- break;
- }
- }
- } catch (StringScanException e) {
- throw new ArgParseException(name, "malformed " + valTypeName()
- + " '" + s + "'");
- }
- scanner.skipWhiteSpace();
- if (!scanner.atEnd()) {
- throw new ArgParseException(name, "malformed " + valTypeName()
- + " '" + s + "'");
- }
- boolean outOfRange = false;
- switch (type) {
- case CHAR:
- case INT:
- case LONG: {
- outOfRange = !withinRange(lval);
- break;
- }
- case FLOAT:
- case DOUBLE: {
- outOfRange = !withinRange(dval);
- break;
- }
- case STRING: {
- outOfRange = !withinRange(sval);
- break;
- }
- case BOOLEAN: {
- outOfRange = !withinRange(bval);
- break;
- }
- }
- if (outOfRange) {
- String errmsg = "value " + s + " not in range ";
- throw new ArgParseException(name, "value '" + s
- + "' not in range " + rangeDesc);
- }
- if (result.getClass().isArray()) {
- switch (type) {
- case BOOLEAN: {
- ((boolean[]) result)[resultIdx] = bval;
- break;
- }
- case CHAR: {
- ((char[]) result)[resultIdx] = (char) lval;
- break;
- }
- case INT: {
- ((int[]) result)[resultIdx] = (int) lval;
- break;
- }
- case LONG: {
- ((long[]) result)[resultIdx] = lval;
- break;
- }
- case FLOAT: {
- ((float[]) result)[resultIdx] = (float) dval;
- break;
- }
- case DOUBLE: {
- ((double[]) result)[resultIdx] = dval;
- break;
- }
- case STRING: {
- ((String[]) result)[resultIdx] = sval;
- break;
- }
- }
- } else {
- switch (type) {
- case BOOLEAN: {
- ((BooleanHolder) result).value = bval;
- break;
- }
- case CHAR: {
- ((CharHolder) result).value = (char) lval;
- break;
- }
- case INT: {
- ((IntHolder) result).value = (int) lval;
- break;
- }
- case LONG: {
- ((LongHolder) result).value = lval;
- break;
- }
- case FLOAT: {
- ((FloatHolder) result).value = (float) dval;
- break;
- }
- case DOUBLE: {
- ((DoubleHolder) result).value = dval;
- break;
- }
- case STRING: {
- ((StringHolder) result).value = sval;
- break;
- }
- }
- }
- }
- }
-
- private String firstHelpOptionName() {
- if (firstHelpOption != null) {
- return firstHelpOption.nameList.name;
- } else {
- return null;
- }
- }
-
- /**
- * Creates an <code>ArgParser</code> with a synopsis string, and the default
- * help options <code>-help</code> and <code>-&#063;</code>.
- *
- * @param synopsisString string that briefly describes program usage, for
- * use by {@link #getHelpMessage getHelpMessage}.
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public ArgParser(String synopsisString) {
- this(synopsisString, true);
- }
-
- /**
- * Creates an <code>ArgParser</code> with a synopsis string. The help
- * options <code>-help</code> and <code>-?</code> are added if
- * <code>defaultHelp</code> is true.
- *
- * @param synopsisString string that briefly describes program usage, for
- * use by {@link #getHelpMessage getHelpMessage}.
- * @param defaultHelp if true, adds the default help options
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public ArgParser(String synopsisString, boolean defaultHelp) {
- matchList = new Vector<Record>(128);
- this.synopsisString = synopsisString;
- if (defaultHelp) {
- addOption("-help,-? %h #displays help information", null);
- defaultHelpOption = firstHelpOption = matchList.get(0);
- }
- }
-
- /**
- * Returns the synopsis string used by the parser. The synopsis string is a
- * short description of how to invoke the program, and usually looks
- * something like
- * <p>
- * <prec> "java somepackage.SomeClass [options] files ..." </prec>
- *
- * <p>
- * It is used in help and error messages.
- *
- * @return synopsis string
- * @see ArgParser#setSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public String getSynopsisString() {
- return synopsisString;
- }
-
- /**
- * Sets the synopsis string used by the parser.
- *
- * @param s new synopsis string
- * @see ArgParser#getSynopsisString
- * @see ArgParser#getHelpMessage
- */
- public void setSynopsisString(String s) {
- synopsisString = s;
- }
-
- /**
- * Indicates whether or not help options are enabled.
- *
- * @return true if help options are enabled
- * @see ArgParser#setHelpOptionsEnabled
- * @see ArgParser#addOption
- */
- public boolean getHelpOptionsEnabled() {
- return helpOptionsEnabled;
- }
-
- /**
- * Enables or disables help options. Help options are those associated with
- * a conversion code of <code>%h</code>. If help options are enabled, and a
- * help option is matched, then the string produced by
- * {@link #getHelpMessage getHelpMessage} is printed to the default print
- * stream and the program exits with code 0. Otherwise, arguments which
- * match help options are ignored.
- *
- * @param enable enables help options if <code>true</code>.
- * @see ArgParser#getHelpOptionsEnabled
- * @see ArgParser#addOption
- * @see ArgParser#setDefaultPrintStream
- */
- public void setHelpOptionsEnabled(boolean enable) {
- helpOptionsEnabled = enable;
- }
-
- /**
- * Returns the default print stream used for outputting help and error
- * information.
- *
- * @return default print stream
- * @see ArgParser#setDefaultPrintStream
- */
- public PrintStream getDefaultPrintStream() {
- return printStream;
- }
-
- /**
- * Sets the default print stream used for outputting help and error
- * information.
- *
- * @param stream new default print stream
- * @see ArgParser#getDefaultPrintStream
- */
- public void setDefaultPrintStream(PrintStream stream) {
- printStream = stream;
- }
-
- /**
- * Gets the indentation used by {@link #getHelpMessage getHelpMessage}.
- *
- * @return number of indentation columns
- * @see ArgParser#setHelpIndentation
- * @see ArgParser#getHelpMessage
- */
- public int getHelpIndentation() {
- return helpIndent;
- }
-
- /**
- * Sets the indentation used by {@link #getHelpMessage getHelpMessage}. This
- * is the number of columns that an option's help information is indented.
- * If the option's name and value information can fit within this number of
- * columns, then all information about the option is placed on one line.
- * Otherwise, the indented help information is placed on a separate line.
- *
- * @param indent number of indentation columns
- * @see ArgParser#getHelpIndentation
- * @see ArgParser#getHelpMessage
- */
- public void setHelpIndentation(int indent) {
- helpIndent = indent;
- }
-
- // public void setTabSpacing (int n)
- // { tabSpacing = n;
- // }
-
- // public int getTabSpacing ()
- // { return tabSpacing;
- // }
-
- private void scanRangeSpec(Record rec, String s)
- throws IllegalArgumentException {
- StringScanner scanner = new StringScanner(s);
- int i0, i = 1;
- char c, c0, c1;
-
- scanner.setStringDelimiters(")],}");
- c = scanner.getc(); // swallow the first '{'
- scanner.skipWhiteSpace();
- while ((c = scanner.peekc()) != '}') {
- RangePnt p0, p1;
-
- if (c == '[' || c == '(') {
- if (rec.convertCode == 'v' || rec.convertCode == 'b') {
- throw new IllegalArgumentException(
- "Sub ranges not supported for %b or %v");
- }
- c0 = scanner.getc(); // record & swallow character
- scanner.skipWhiteSpace();
- p0 = new RangePnt(scanner, rec.type);
- scanner.skipWhiteSpace();
- if (scanner.getc() != ',') {
- throw new IllegalArgumentException(
- "Missing ',' in subrange specification");
- }
- p1 = new RangePnt(scanner, rec.type);
- scanner.skipWhiteSpace();
- if ((c1 = scanner.getc()) != ']' && c1 != ')') {
- throw new IllegalArgumentException("Unterminated subrange");
- }
- if (c0 == '(') {
- p0.setClosed(false);
- }
- if (c1 == ')') {
- p1.setClosed(false);
- }
- rec.addRangeAtom(new RangeAtom(p0, p1, rec.type));
- } else {
- scanner.skipWhiteSpace();
- p0 = new RangePnt(scanner, rec.type);
- rec.addRangeAtom(new RangeAtom(p0));
- }
- scanner.skipWhiteSpace();
- if ((c = scanner.peekc()) == ',') {
- scanner.getc();
- scanner.skipWhiteSpace();
- } else if (c != '}') {
- throw new IllegalArgumentException(
- "Range spec: ',' or '}' expected");
- }
- }
- if (rec.numRangeAtoms() == 1) {
- rec.rangeDesc = s.substring(1, s.length() - 1);
- } else {
- rec.rangeDesc = s;
- }
- }
-
- private int defaultResultType(char convertCode) {
- switch (convertCode) {
- case 'i':
- case 'o':
- case 'd':
- case 'x': {
- return Record.LONG;
- }
- case 'c': {
- return Record.CHAR;
- }
- case 'v':
- case 'b': {
- return Record.BOOLEAN;
- }
- case 'f': {
- return Record.DOUBLE;
- }
- case 's': {
- return Record.STRING;
- }
- }
- return Record.NOTYPE;
- }
-
- /**
- * Adds a new option description to the parser. The method takes two
- * arguments: a specification string, and a result holder in which to store
- * the associated value.
- *
- * <p>
- * The specification string has the general form
- *
- * <p>
- * <var>optionNames</var> <code>%</code><var>conversionCode</var> [
- * <code>{</code><var>rangeSpec</var><code>}</code>] [<code>X</code>
- * <var>multiplier</var>] [<code>#</code><var>valueDescription</var>] [
- * <code>#</code><var>optionDescription</var>] </code>
- *
- * <p>
- * where
- * <ul>
- * <p>
- * <li><var>optionNames</var> is a comma-separated list of names for the
- * option (such as <code>-f, --file</code>).
- *
- * <p>
- * <li><var>conversionCode</var> is a single letter, following a
- * <code>%</code> character, specifying information about what value the
- * option requires:
- *
- * <table>
- * <tr>
- * <td><code>%f</code></td>
- * <td>a floating point number</td>
- * <tr>
- * <td><code>%i</code></td>
- * <td>an integer, in either decimal, hex (if preceeded by <code>0x</code>),
- * or octal (if preceeded by <code>0</code>)</td>
- * <tr valign=top>
- * <td><code>%d</code></td>
- * <td>a decimal integer</td>
- * <tr valign=top>
- * <td><code>%o</code></td>
- * <td>an octal integer</td>
- * <tr valign=top>
- * <td><code>%h</code></td>
- * <td>a hex integer (without the preceeding <code>0x</code>)</td>
- * <tr valign=top>
- * <td><code>%c</code></td>
- * <td>a single character, including escape sequences (such as
- * <code>\n</code> or <code>\007</code>), and optionally enclosed in single
- * quotes
- * <tr valign=top>
- * <td><code>%b</code></td>
- * <td>a boolean value (<code>true</code> or <code>false</code>)</td>
- * <tr valign=top>
- * <td><code>%s</code></td>
- * <td>a string. This will be the argument string itself (or its remainder,
- * in the case of a single word option)</td>
- * <tr valign=top>
- * <td><code>%v</code></td>
- * <td>no explicit value is expected, but a boolean value of
- * <code>true</code> (by default) will be stored into the associated result
- * holder if this option is matched. If one wishes to have a value of
- * <code>false</code> stored instead, then the <code>%v</code> should be
- * followed by a "range spec" containing <code>false</code>, as in
- * <code>%v{false}</code>.
- * </table>
- *
- * <p>
- * <li><var>rangeSpec</var> is an optional range specification, placed
- * inside curly braces, consisting of a comma-separated list of range items
- * each specifying permissible values for the option. A range item may be an
- * individual value, or it may itself be a subrange, consisting of two
- * individual values, separated by a comma, and enclosed in square or round
- * brackets. Square and round brackets denote closed and open endpoints of a
- * subrange, indicating that the associated endpoint value is included or
- * excluded from the subrange. The values specified in the range spec need
- * to be consistent with the type of value expected by the option.
- *
- * <p>
- * <b>Examples:</b>
- *
- * <p>
- * A range spec of <code>{2,4,8,16}</code> for an integer value will allow
- * the integers 2, 4, 8, or 16.
- *
- * <p>
- * A range spec of <code>{[-1.0,1.0]}</code> for a floating point value will
- * allow any floating point number in the range -1.0 to 1.0.
- *
- * <p>
- * A range spec of <code>{(-88,100],1000}</code> for an integer value will
- * allow values > -88 and <= 100, as well as 1000.
- *
- * <p>
- * A range spec of <code>{"foo", "bar", ["aaa","zzz")} </code> for a string
- * value will allow strings equal to <code>"foo"</code> or
- * <code>"bar"</code>, plus any string lexically greater than or equal to
- * <code>"aaa"</code> but less then <code>"zzz"</code>.
- *
- * <p>
- * <li><var>multiplier</var> is an optional integer, following a
- * <code>X</code> character, indicating the number of values which the
- * option expects. If the multiplier is not specified, it is assumed to be
- * 1. If the multiplier value is greater than 1, then the result holder
- * should be either an array (of appropriate type) with a length greater
- * than or equal to the multiplier value, or a <code>java.util.Vector</code>
- * <a href=#vectorHolder>as discussed below</a>.
- *
- * <p>
- * <li><var>valueDescription</var> is an optional description of the
- * option's value requirements, and consists of all characters between two
- * <code>#</code> characters. The final <code>#</code> character initiates
- * the <i>option description</i>, which may be empty. The value description
- * is used in <a href=#helpInfo>generating help messages</a>.
- *
- * <p>
- * <li><var>optionDescription</var> is an optional description of the option
- * itself, consisting of all characters between a <code>#</code> character
- * and the end of the specification string. The option description is used
- * in <a href=#helpInfo>generating help messages</a>.
- * </ul>
- *
- * <p>
- * The result holder must be an object capable of holding a value compatible
- * with the conversion code, or it must be a <code>java.util.Vector</code>.
- * When the option is matched, its associated value is placed in the result
- * holder. If the same option is matched repeatedly, the result holder value
- * will be overwritten, unless the result holder is a
- * <code>java.util.Vector</code>, in which case new holder objects for each
- * match will be allocated and added to the vector. Thus if multiple
- * instances of an option are desired by the program, the result holder
- * should be a <code>java.util.Vector</code>.
- *
- * <p>
- * If the result holder is not a <code>Vector</code>, then it must
- * correspond as follows to the conversion code:
- *
- * <table>
- * <tr valign=top>
- * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, <code>%o</code></td>
- * <td>{@link argparser.IntHolder IntHolder}, {@link argparser.LongHolder
- * LongHolder}, <code>int[]</code>, or <code>long[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%f</code></td>
- * <td>{@link argparser.FloatHolder FloatHolder},
- * {@link argparser.DoubleHolder DoubleHolder}, <code>float[]</code>, or
- * <code>double[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%b</code>, <code>%v</code></td>
- * <td>{@link argparser.BooleanHolder BooleanHolder} or
- * <code>boolean[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%s</code></td>
- * <td>{@link argparser.StringHolder StringHolder} or <code>String[]</code></td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%c</code></td>
- * <td>{@link argparser.CharHolder CharHolder} or <code>char[]</code></td>
- * </tr>
- * </table>
- *
- * <p>
- * In addition, if the multiplier is greater than 1, then only the array
- * type indicated above may be used, and the array must be at least as long
- * as the multiplier.
- *
- * <p>
- * <a name=vectorHolder>If the result holder is a <code>Vector</code>, then
- * the system will create an appropriate result holder object and add it to
- * the vector. Multiple occurances of the option will cause multiple results
- * to be added to the vector.
- *
- * <p>
- * The object allocated by the system to store the result will correspond to
- * the conversion code as follows:
- *
- * <table>
- * <tr valign=top>
- * <td><code>%i</code>, <code>%d</code>, <code>%x</code>, <code>%o</code></td>
- * <td>{@link argparser.LongHolder LongHolder}, or <code>long[]</code> if
- * the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%f</code></td>
- * <td>{@link argparser.DoubleHolder DoubleHolder}, or <code>double[]</code>
- * if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%b</code>, <code>%v</code></td>
- * <td>{@link argparser.BooleanHolder BooleanHolder}, or
- * <code>boolean[]</code> if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%s</code></td>
- * <td>{@link argparser.StringHolder StringHolder}, or <code>String[]</code>
- * if the multiplier value exceeds 1</td>
- * </tr>
- *
- * <tr valign=top>
- * <td><code>%c</code></td>
- * <td>{@link argparser.CharHolder CharHolder}, or <code>char[]</code> if
- * the multiplier value exceeds 1</td>
- * </tr>
- * </table>
- *
- * @param spec the specification string
- * @param resHolder object in which to store the associated value
- * @throws IllegalArgumentException if there is an error in the
- * specification or if the result holder is of an invalid type.
- */
- public void addOption(String spec, Object resHolder)
- throws IllegalArgumentException {
- // null terminated string is easier to parse
- StringScanner scanner = new StringScanner(spec);
- Record rec = null;
- NameDesc nameTail = null;
- NameDesc ndesc;
- int i0, i1;
- char c;
-
- do {
- ndesc = new NameDesc();
- boolean nameEndsInWhiteSpace = false;
-
- scanner.skipWhiteSpace();
- i0 = scanner.getIndex();
- while (!Character.isWhitespace(c = scanner.getc()) && c != ','
- && c != '%' && c != '\000')
- ;
- i1 = scanner.getIndex();
- if (c != '\000') {
- i1--;
- }
- if (i0 == i1) { // then c is one of ',' '%' or '\000'
- throw new IllegalArgumentException("Null option name given");
- }
- if (Character.isWhitespace(c)) {
- nameEndsInWhiteSpace = true;
- scanner.skipWhiteSpace();
- c = scanner.getc();
- }
- if (c == '\000') {
- throw new IllegalArgumentException(
- "No conversion character given");
- }
- if (c != ',' && c != '%') {
- throw new IllegalArgumentException("Names not separated by ','");
- }
- ndesc.name = scanner.substring(i0, i1);
- if (rec == null) {
- rec = new Record();
- rec.nameList = ndesc;
- } else {
- nameTail.next = ndesc;
- }
- nameTail = ndesc;
- ndesc.oneWord = !nameEndsInWhiteSpace;
- } while (c != '%');
-
- if (!nameTail.oneWord) {
- for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
- ndesc.oneWord = false;
- }
- }
- c = scanner.getc();
- if (c == '\000') {
- throw new IllegalArgumentException("No conversion character given");
- }
- if (validConversionCodes.indexOf(c) == -1) {
- throw new IllegalArgumentException("Conversion code '" + c
- + "' not one of '" + validConversionCodes + "'");
- }
- rec.convertCode = c;
-
- if (resHolder instanceof Vector) {
- rec.vectorResult = true;
- rec.type = defaultResultType(rec.convertCode);
- } else {
- switch (rec.convertCode) {
- case 'i':
- case 'o':
- case 'd':
- case 'x': {
- if (resHolder instanceof LongHolder
- || resHolder instanceof long[]) {
- rec.type = Record.LONG;
- } else if (resHolder instanceof IntHolder
- || resHolder instanceof int[]) {
- rec.type = Record.INT;
- } else {
- throw new IllegalArgumentException(
- "Invalid result holder for %" + c);
- }
- break;
- }
- case 'c': {
- if (!(resHolder instanceof CharHolder)
- && !(resHolder instanceof char[])) {
- throw new IllegalArgumentException(
- "Invalid result holder for %c");
- }
- rec.type = Record.CHAR;
- break;
- }
- case 'v':
- case 'b': {
- if (!(resHolder instanceof BooleanHolder)
- && !(resHolder instanceof boolean[])) {
- throw new IllegalArgumentException(
- "Invalid result holder for %" + c);
- }
- rec.type = Record.BOOLEAN;
- break;
- }
- case 'f': {
- if (resHolder instanceof DoubleHolder
- || resHolder instanceof double[]) {
- rec.type = Record.DOUBLE;
- } else if (resHolder instanceof FloatHolder
- || resHolder instanceof float[]) {
- rec.type = Record.FLOAT;
- } else {
- throw new IllegalArgumentException(
- "Invalid result holder for %f");
- }
- break;
- }
- case 's': {
- if (!(resHolder instanceof StringHolder)
- && !(resHolder instanceof String[])) {
- throw new IllegalArgumentException(
- "Invalid result holder for %s");
- }
- rec.type = Record.STRING;
- break;
- }
- case 'h': { // resHolder is ignored for this type
- break;
- }
- }
- }
- if (rec.convertCode == 'h') {
- rec.resHolder = null;
- } else {
- rec.resHolder = resHolder;
- }
-
- scanner.skipWhiteSpace();
- // get the range specification, if any
- if (scanner.peekc() == '{') {
- if (rec.convertCode == 'h') {
- throw new IllegalArgumentException(
- "Ranges not supported for %h");
- }
- // int bcnt = 0;
- i0 = scanner.getIndex(); // beginning of range spec
- do {
- c = scanner.getc();
- if (c == '\000') {
- throw new IllegalArgumentException(
- "Unterminated range specification");
- }
- // else if (c=='[' || c=='(')
- // { bcnt++;
- // }
- // else if (c==']' || c==')')
- // { bcnt--;
- // }
- // if ((rec.convertCode=='v'||rec.convertCode=='b') && bcnt>1)
- // { throw new IllegalArgumentException
- // ("Sub ranges not supported for %b or %v");
- // }
- } while (c != '}');
- // if (c != ']')
- // { throw new IllegalArgumentException
- // ("Range specification must end with ']'");
- // }
- i1 = scanner.getIndex(); // end of range spec
- scanRangeSpec(rec, scanner.substring(i0, i1));
- if (rec.convertCode == 'v' && rec.rangeList != null) {
- rec.vval = rec.rangeList.low.bval;
- }
- }
- // check for value multiplicity information, if any
- if (scanner.peekc() == 'X') {
- if (rec.convertCode == 'h') {
- throw new IllegalArgumentException(
- "Multipliers not supported for %h");
- }
- scanner.getc();
- try {
- rec.numValues = (int) scanner.scanInt();
- } catch (StringScanException e) {
- throw new IllegalArgumentException("Malformed value multiplier");
- }
- if (rec.numValues <= 0) {
- throw new IllegalArgumentException(
- "Value multiplier number must be > 0");
- }
- } else {
- rec.numValues = 1;
- }
- if (rec.numValues > 1) {
- for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
- if (ndesc.oneWord) {
- throw new IllegalArgumentException(
- "Multiplier value incompatible with one word option "
- + ndesc.name);
- }
- }
- }
- if (resHolder != null && resHolder.getClass().isArray()) {
- if (Array.getLength(resHolder) < rec.numValues) {
- throw new IllegalArgumentException(
- "Result holder array must have a length >= "
- + rec.numValues);
- }
- } else {
- if (rec.numValues > 1 && !(resHolder instanceof Vector)) {
- throw new IllegalArgumentException(
- "Multiplier requires result holder to be an array of length >= "
- + rec.numValues);
- }
- }
-
- // skip white space following conversion information
- scanner.skipWhiteSpace();
+ }
+
+
+ Object getResultHolder (String arg)
+ {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.resHolder : null;
+ }
+
+ String getOptionName (String arg)
+ {
+ ObjectHolder ndescHolder = new ObjectHolder();
+ Record rec = getRecord(arg, ndescHolder);
+ return (rec != null) ? ((NameDesc)ndescHolder.value).name : null;
+ }
+
+ String getOptionRangeDesc (String arg)
+ {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.rangeDesc : null;
+ }
+
+ String getOptionTypeName (String arg)
+ {
+ Record rec = getRecord(arg, null);
+ return (rec != null) ? rec.valTypeName() : null;
+ }
+
+ private Object createResultHolder (Record rec)
+ {
+ if (rec.numValues == 1)
+ { switch (rec.type)
+ { case Record.LONG:
+ { return new LongHolder();
+ }
+ case Record.CHAR:
+ { return new CharHolder();
+ }
+ case Record.BOOLEAN:
+ { return new BooleanHolder();
+ }
+ case Record.DOUBLE:
+ { return new DoubleHolder();
+ }
+ case Record.STRING:
+ { return new StringHolder();
+ }
+ }
+ }
+ else
+ { switch (rec.type)
+ { case Record.LONG:
+ { return new long[rec.numValues];
+ }
+ case Record.CHAR:
+ { return new char[rec.numValues];
+ }
+ case Record.BOOLEAN:
+ { return new boolean[rec.numValues];
+ }
+ case Record.DOUBLE:
+ { return new double[rec.numValues];
+ }
+ case Record.STRING:
+ { return new String[rec.numValues];
+ }
+ }
+ }
+ return null; // can't happen
+ }
+
+ static void stringToArgs (Vector<String> vec, String s,
+ boolean allowQuotedStrings)
+ throws StringScanException
+ {
+ StringScanner scanner = new StringScanner(s);
+ scanner.skipWhiteSpace();
+ while (!scanner.atEnd())
+ { if (allowQuotedStrings)
+ { vec.add (scanner.scanString());
+ }
+ else
+ { vec.add (scanner.scanNonWhiteSpaceString());
+ }
+ scanner.skipWhiteSpace();
+ }
+ }
+
+ /**
+ * Reads in a set of strings from a reader and prepends them to an
+ * argument list. Strings are delimited by either whitespace or
+ * double quotes <code>"</code>. The character <code>#</code> acts as
+ * a comment character, causing input to the end of the current line to
+ * be ignored.
+ *
+ * @param reader Reader from which to read the strings
+ * @param args Initial set of argument values. Can be
+ * specified as <code>null</code>.
+ * @throws IOException if an error occured while reading.
+ */
+ public static String[] prependArgs (Reader reader, String[] args)
+ throws IOException
+ {
+ if (args == null)
+ { args = new String[0];
+ }
+ LineNumberReader lineReader = new LineNumberReader (reader);
+ Vector<String> vec = new Vector<String>(100, 100);
+ String line;
+ int i, k;
+
+ while ((line = lineReader.readLine()) != null)
+ { int commentIdx = line.indexOf ("#");
+ if (commentIdx != -1)
+ { line = line.substring (0, commentIdx);
+ }
+ try
+ { stringToArgs (vec, line, /*allowQuotedStings=*/true);
+ }
+ catch (StringScanException e)
+ { throw new IOException (
+ "malformed string, line "+lineReader.getLineNumber());
+ }
+ }
+ String[] result = new String[vec.size()+args.length];
+ for (i=0; i<vec.size(); i++)
+ { result[i] = (String)vec.get(i);
+ }
+ for (k=0; k<args.length; k++)
+ { result[i++] = args[k];
+ }
+ return result;
+ }
+
+ /**
+ * Reads in a set of strings from a file and prepends them to an
+ * argument list. Strings are delimited by either whitespace or double
+ * quotes <code>"</code>. The character <code>#</code> acts as a
+ * comment character, causing input to the end of the current line to
+ * be ignored.
+ *
+ * @param file File to be read
+ * @param args Initial set of argument values. Can be
+ * specified as <code>null</code>.
+ * @throws IOException if an error occured while reading the file.
+ */
+ public static String[] prependArgs (File file, String[] args)
+ throws IOException
+ {
+ if (args == null)
+ { args = new String[0];
+ }
+ if (!file.canRead())
+ { return args;
+ }
+ try
+ { return prependArgs (new FileReader (file), args);
+ }
+ catch (IOException e)
+ { throw new IOException (
+"File " + file.getName() + ": " + e.getMessage());
+ }
+ }
+
+ /**
+ * Sets the parser's error message.
+ *
+ * @param s Error message
+ */
+ protected void setError (String msg)
+ {
+ errMsg = msg;
+ }
+
+ /**
+ * Prints an error message, along with a pointer to help options,
+ * if available, and causes the program to exit with code 1.
+ */
+ public void printErrorAndExit (String msg)
+ {
+ if (helpOptionsEnabled && firstHelpOptionName() != null)
+ { msg += "\nUse "+firstHelpOptionName()+" for help information";
+ }
+ if (printStream != null)
+ { printStream.println (msg);
+ }
+ System.exit(1);
+ }
+
+ /**
+ * Matches arguments within an argument list.
+ *
+ * <p>In the event of an erroneous or unmatched argument, the method
+ * prints a message and exits the program with code 1.
+ *
+ * <p>If help options are enabled and one of the arguments matches a
+ * help option, then the result of {@link #getHelpMessage
+ * getHelpMessage} is printed to the default print stream and the
+ * program exits with code 0. If help options are not enabled, they
+ * are ignored.
+ *
+ * @param args argument list
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public void matchAllArgs (String[] args)
+ {
+ matchAllArgs (args, 0, EXIT_ON_UNMATCHED | EXIT_ON_ERROR);
+ }
+
+ /**
+ * Matches arguments within an argument list and returns
+ * those which were not matched. The matching starts at a location
+ * in <code>args</code> specified by <code>idx</code>, and
+ * unmatched arguments are returned in a String array.
+ *
+ * <p>In the event of an erroneous argument, the method either prints a
+ * message and exits the program (if {@link #EXIT_ON_ERROR} is
+ * set in <code>exitFlags</code>)
+ * or terminates the matching and creates a error message that
+ * can be retrieved by {@link #getErrorMessage}.
+ *
+ * <p>In the event of an umatched argument, the method will print a
+ * message and exit if {@link #EXIT_ON_UNMATCHED} is set
+ * in <code>errorFlags</code>.
+ * Otherwise, the unmatched argument will be appended to the returned
+ * array of unmatched values, and the matching will continue at the
+ * next location.
+ *
+ * <p>If help options are enabled and one of the arguments matches a
+ * help option, then the result of {@link #getHelpMessage
+ * getHelpMessage} is printed to the the default print stream and the
+ * program exits with code 0. If help options are not enabled, then
+ * they will not be matched.
+ *
+ * @param args argument list
+ * @param idx starting location in list
+ * @param exitFlags conditions causing the program to exit. Should be
+ * an or-ed combintion of {@link #EXIT_ON_ERROR} or {@link
+ * #EXIT_ON_UNMATCHED}.
+ * @return array of arguments that were not matched, or
+ * <code>null</code> if all arguments were successfully matched
+ * @see ArgParser#getErrorMessage
+ * @see ArgParser#getDefaultPrintStream
+ */
+ public String[] matchAllArgs (String[] args, int idx, int exitFlags)
+ {
+ Vector<String> unmatched = new Vector<String>(10);
+
+ while (idx < args.length)
+ { try
+ { idx = matchArg (args, idx);
+ if (unmatchedArg != null)
+ { if ((exitFlags & EXIT_ON_UNMATCHED) != 0)
+ { printErrorAndExit (
+ "Unrecognized argument: " + unmatchedArg);
+ }
+ else
+ { unmatched.add (unmatchedArg);
+ }
+ }
+ }
+ catch (ArgParseException e)
+ { if ((exitFlags & EXIT_ON_ERROR) != 0)
+ { printErrorAndExit (e.getMessage());
+ }
+ break;
+ }
+ }
+ if (unmatched.size() == 0)
+ { return null;
+ }
+ else
+ { return (String[])unmatched.toArray(new String[0]);
+ }
+ }
+
+ /**
+ * Matches one option starting at a specified location in an argument
+ * list. The method returns the location in the list where the next
+ * match should begin.
+ *
+ * <p>In the event of an erroneous argument, the method throws
+ * an {@link argparser.ArgParseException ArgParseException}
+ * with an appropriate error message. This error
+ * message can also be retrieved using
+ * {@link #getErrorMessage getErrorMessage}.
+ *
+ * <p>In the event of an umatched argument, the method will return idx
+ * + 1, and {@link #getUnmatchedArgument getUnmatchedArgument} will
+ * return a copy of the unmatched argument. If an argument is matched,
+ * {@link #getUnmatchedArgument getUnmatchedArgument} will return
+ * <code>null</code>.
+ *
+ * <p>If help options are enabled and the argument matches a help
+ * option, then the result of {@link #getHelpMessage getHelpMessage} is printed to
+ * the the default print stream and the program exits with code 0. If
+ * help options are not enabled, then they are ignored.
+ *
+ * @param args argument list
+ * @param idx location in list where match should start
+ * @return location in list where next match should start
+ * @throws ArgParseException if there was an error performing
+ * the match (such as improper or insufficient values).
+ * @see ArgParser#setDefaultPrintStream
+ * @see ArgParser#getHelpOptionsEnabled
+ * @see ArgParser#getErrorMessage
+ * @see ArgParser#getUnmatchedArgument
+ */
+ @SuppressWarnings("unchecked")
+ public int matchArg (String[] args, int idx)
+ throws ArgParseException
+ {
+ unmatchedArg = null;
+ setError (null);
+ try
+ { ObjectHolder ndescHolder = new ObjectHolder();
+ Record rec = getRecord (args[idx], ndescHolder);
+ if (rec == null || (rec.convertCode=='h' && !helpOptionsEnabled))
+ { // didn't match
+ unmatchedArg = new String(args[idx]);
+ return idx+1;
+ }
+ NameDesc ndesc = (NameDesc)ndescHolder.value;
+ Object result;
+ if (rec.resHolder instanceof Vector)
+ { result = createResultHolder (rec);
+ }
+ else
+ { result = rec.resHolder;
+ }
+ if (rec.convertCode == 'h')
+ { if (helpOptionsEnabled)
+ { printStream.println (getHelpMessage());
+ System.exit (0);
+ }
+ else
+ { return idx+1;
+ }
+ }
+ else if (rec.convertCode != 'v')
+ { if (ndesc.oneWord)
+ { rec.scanValue (
+ result, ndesc.name,
+ args[idx].substring (ndesc.name.length()), 0);
+ }
+ else
+ { if (idx+rec.numValues >= args.length)
+ { throw new ArgParseException (
+ ndesc.name, "requires " + rec.numValues + " value" +
+ (rec.numValues > 1 ? "s" : ""));
+ }
+ for (int k=0; k<rec.numValues; k++)
+ { rec.scanValue (result, ndesc.name, args[++idx], k);
+ }
+ }
+ }
+ else
+ { if (rec.resHolder instanceof BooleanHolder)
+ { ((BooleanHolder)result).value = rec.vval;
+ }
+ else
+ { for (int k=0; k<rec.numValues; k++)
+ { ((boolean[])result)[k] = rec.vval;
+ }
+ }
+ }
+ if (rec.resHolder instanceof Vector)
+ { ((Vector<Object>)rec.resHolder).add (result);
+ }
+ }
+ catch (ArgParseException e)
+ { setError (e.getMessage());
+ throw e;
+ }
+ return idx+1;
+ }
+
+ private String spaceString (int n)
+ {
+ StringBuffer sbuf = new StringBuffer(n);
+ for (int i=0; i<n; i++)
+ { sbuf.append(' ');
+ }
+ return sbuf.toString();
+ }
+
+// public String getShortHelpMessage ()
+// {
+// String s;
+// Record rec;
+// NameDesc ndesc;
+// int initialIndent = 8;
+// int col = initialIndent;
+
+// if (maxcols <= 0)
+// { maxcols = 80;
+// }
+// if (matchList.size() > 0)
+// { ps.print (spaceString(initialIndent));
+// }
+// for (int i=0; i<matchList.size(); i++)
+// { rec = (Record)matchList.get(i);
+// s = "[";
+// for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+// { s = s + ndesc.name;
+// if (ndesc.oneWord == false)
+// { s = s + " ";
+// }
+// if (ndesc.next != null)
+// { s = s + ",";
+// }
+// }
+// if (rec.convertCode != 'v' && rec.convertCode != 'h')
+// { if (rec.valueDesc != null)
+// { s += rec.valueDesc;
+// }
+// else
+// { s = s + "<" + rec.valTypeName() + ">";
+// if (rec.numValues > 1)
+// { s += "X" + rec.numValues;
+// }
+// }
+// }
+// s = s + "]";
+// /*
+// (col+=s.length()) > (maxcols-1) => we will spill over edge.
+// we use (maxcols-1) because if we go right to the edge
+// (maxcols), we get wrap new line inserted "for us".
+// i != 0 means we print the first entry, no matter
+// how long it is. Subsequent entries are printed
+// full length anyway. */
+
+// if ((col+=s.length()) > (maxcols-1) && i != 0)
+// { col = initialIndent+s.length();
+// ps.print ("\n" + spaceString(initialIndent));
+// }
+// ps.print (s);
+// }
+// if (matchList.size() > 0)
+// { ps.print ('\n');
+// ps.flush();
+// }
+// }
+
+ /**
+ * Returns a string describing the allowed options
+ * in detail.
+ *
+ * @return help information string.
+ */
+ public String getHelpMessage ()
+ {
+ Record rec;
+ NameDesc ndesc;
+ boolean hasOneWordAlias = false;
+ String s;
+
+ s = "Usage: " + synopsisString + "\n";
+ s += "Options include:\n\n";
+ for (int i=0; i<matchList.size(); i++)
+ { String optionInfo = "";
+ rec = (Record)matchList.get(i);
+ if (rec.convertCode=='h' && !helpOptionsEnabled)
+ { continue;
+ }
+ for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ { if (ndesc.oneWord)
+ { hasOneWordAlias = true;
+ break;
+ }
+ }
+ for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
+ { optionInfo += ndesc.name;
+ if (hasOneWordAlias && !ndesc.oneWord)
+ { optionInfo += " ";
+ }
+ if (ndesc.next != null)
+ { optionInfo += ",";
+ }
+ }
+ if (!hasOneWordAlias)
+ { optionInfo += " ";
+ }
+ if (rec.convertCode != 'v' && rec.convertCode != 'h')
+ { if (rec.valueDesc != null)
+ { optionInfo += rec.valueDesc;
+ }
+ else
+ { if (rec.rangeDesc != null)
+ { optionInfo += "<" + rec.valTypeName() + " "
+ + rec.rangeDesc + ">";
+ }
+ else
+ { optionInfo += "<" + rec.valTypeName() + ">";
+ }
+ }
+ }
+ if (rec.numValues > 1)
+ { optionInfo += "X" + rec.numValues;
+ }
+ s += optionInfo;
+ if (rec.helpMsg.length() > 0)
+ { int pad = helpIndent - optionInfo.length();
+ if (pad < 2)
+ { //s += '\n';
+ pad = helpIndent;
+ }
+// s += spaceString(pad) + rec.helpMsg;
+ s += spaceString(4) + rec.helpMsg;
+ }
+ s += '\n';
+ }
+ return s;
+ }
+
+ /**
+ * Returns the parser's error message. This is automatically
+ * set whenever an error is encountered in <code>matchArg</code>
+ * or <code>matchAllArgs</code>, and is automatically set to
+ * <code>null</code> at the beginning of these methods.
+ *
+ * @return error message
+ */
+ public String getErrorMessage()
+ {
+ return errMsg;
+ }
+
+ /**
+ * Returns the value of an unmatched argument discovered {@link
+ * #matchArg matchArg} or {@link #matchAllArgs(String[],int,int)
+ * matchAllArgs}. If there was no unmatched argument,
+ * <code>null</code> is returned.
+ *
+ * @return unmatched argument
+ */
+ public String getUnmatchedArgument()
+ {
+ return unmatchedArg;
+ }
+}
- // get the help message, if any
- if (!scanner.atEnd()) {
- if (scanner.getc() != '#') {
- throw new IllegalArgumentException(
- "Illegal character(s), expecting '#'");
- }
- String helpInfo = scanner.substring(scanner.getIndex());
- // look for second '#'. If there is one, then info
- // between the first and second '#' is the value descriptor.
- int k = helpInfo.indexOf("#");
- if (k != -1) {
- rec.valueDesc = helpInfo.substring(0, k);
- rec.helpMsg = helpInfo.substring(k + 1);
- } else {
- rec.helpMsg = helpInfo;
- }
- } else {
- rec.helpMsg = "";
- }
-
- // parse helpMsg for required/optional information if present
- // default to required
- if (rec.helpMsg.indexOf("(optional") != -1) {
- rec.required = false;
- }
-
- // add option information to match list
- if (rec.convertCode == 'h' && firstHelpOption == defaultHelpOption) {
- matchList.remove(defaultHelpOption);
- firstHelpOption = rec;
- }
- matchList.add(rec);
- }
-
- Record lastMatchRecord() {
- return (Record) matchList.lastElement();
- }
-
- private Record getRecord(String arg, ObjectHolder ndescHolder) {
- NameDesc ndesc;
- for (int i = 0; i < matchList.size(); i++) {
- Record rec = (Record) matchList.get(i);
- for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
- if (rec.convertCode != 'v' && ndesc.oneWord) {
- if (arg.startsWith(ndesc.name)) {
- if (ndescHolder != null) {
- ndescHolder.value = ndesc;
- }
- return rec;
- }
- } else {
- if (arg.equals(ndesc.name)) {
- if (ndescHolder != null) {
- ndescHolder.value = ndesc;
- }
- return rec;
- }
- }
- }
- }
- return null;
- }
-
- public void checkRequiredArgs() {
- for (int i = 1; i < matchList.size(); i++) {
- Record rec = (Record) matchList.get(i);
- StringHolder myString = (StringHolder) rec.resHolder;
- if (((myString.value == null) || (myString.value.equals("")))
- && (rec.required)) {
- printErrorAndExit("Required parameter " + rec.nameList.name
- + " is not specified.");
- }
- }
- }
-
- Object getResultHolder(String arg) {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.resHolder : null;
- }
-
- String getOptionName(String arg) {
- ObjectHolder ndescHolder = new ObjectHolder();
- Record rec = getRecord(arg, ndescHolder);
- return (rec != null) ? ((NameDesc) ndescHolder.value).name : null;
- }
-
- String getOptionRangeDesc(String arg) {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.rangeDesc : null;
- }
-
- String getOptionTypeName(String arg) {
- Record rec = getRecord(arg, null);
- return (rec != null) ? rec.valTypeName() : null;
- }
-
- private Object createResultHolder(Record rec) {
- if (rec.numValues == 1) {
- switch (rec.type) {
- case Record.LONG: {
- return new LongHolder();
- }
- case Record.CHAR: {
- return new CharHolder();
- }
- case Record.BOOLEAN: {
- return new BooleanHolder();
- }
- case Record.DOUBLE: {
- return new DoubleHolder();
- }
- case Record.STRING: {
- return new StringHolder();
- }
- }
- } else {
- switch (rec.type) {
- case Record.LONG: {
- return new long[rec.numValues];
- }
- case Record.CHAR: {
- return new char[rec.numValues];
- }
- case Record.BOOLEAN: {
- return new boolean[rec.numValues];
- }
- case Record.DOUBLE: {
- return new double[rec.numValues];
- }
- case Record.STRING: {
- return new String[rec.numValues];
- }
- }
- }
- return null; // can't happen
- }
-
- static void stringToArgs(Vector<String> vec, String s,
- boolean allowQuotedStrings) throws StringScanException {
- StringScanner scanner = new StringScanner(s);
- scanner.skipWhiteSpace();
- while (!scanner.atEnd()) {
- if (allowQuotedStrings) {
- vec.add(scanner.scanString());
- } else {
- vec.add(scanner.scanNonWhiteSpaceString());
- }
- scanner.skipWhiteSpace();
- }
- }
-
- /**
- * Reads in a set of strings from a reader and prepends them to an argument
- * list. Strings are delimited by either whitespace or double quotes
- * <code>"</code>. The character <code>#</code> acts as a comment character,
- * causing input to the end of the current line to be ignored.
- *
- * @param reader Reader from which to read the strings
- * @param args Initial set of argument values. Can be specified as
- * <code>null</code>.
- * @throws IOException if an error occured while reading.
- */
- public static String[] prependArgs(Reader reader, String[] args)
- throws IOException {
- if (args == null) {
- args = new String[0];
- }
- LineNumberReader lineReader = new LineNumberReader(reader);
- Vector<String> vec = new Vector<String>(100, 100);
- String line;
- int i, k;
-
- while ((line = lineReader.readLine()) != null) {
- int commentIdx = line.indexOf("#");
- if (commentIdx != -1) {
- line = line.substring(0, commentIdx);
- }
- try {
- stringToArgs(vec, line, /* allowQuotedStings= */true);
- } catch (StringScanException e) {
- throw new IOException("malformed string, line "
- + lineReader.getLineNumber());
- }
- }
- String[] result = new String[vec.size() + args.length];
- for (i = 0; i < vec.size(); i++) {
- result[i] = (String) vec.get(i);
- }
- for (k = 0; k < args.length; k++) {
- result[i++] = args[k];
- }
- return result;
- }
-
- /**
- * Reads in a set of strings from a file and prepends them to an argument
- * list. Strings are delimited by either whitespace or double quotes
- * <code>"</code>. The character <code>#</code> acts as a comment character,
- * causing input to the end of the current line to be ignored.
- *
- * @param file File to be read
- * @param args Initial set of argument values. Can be specified as
- * <code>null</code>.
- * @throws IOException if an error occured while reading the file.
- */
- public static String[] prependArgs(File file, String[] args)
- throws IOException {
- if (args == null) {
- args = new String[0];
- }
- if (!file.canRead()) {
- return args;
- }
- try {
- return prependArgs(new FileReader(file), args);
- } catch (IOException e) {
- throw new IOException("File " + file.getName() + ": "
- + e.getMessage());
- }
- }
-
- /**
- * Sets the parser's error message.
- *
- * @param s Error message
- */
- protected void setError(String msg) {
- errMsg = msg;
- }
-
- /**
- * Prints an error message, along with a pointer to help options, if
- * available, and causes the program to exit with code 1.
- */
- public void printErrorAndExit(String msg) {
- if (helpOptionsEnabled && firstHelpOptionName() != null) {
- msg += "\nUse " + firstHelpOptionName() + " for help information";
- }
- if (printStream != null) {
- printStream.println(msg);
- }
- System.exit(1);
- }
-
- /**
- * Matches arguments within an argument list.
- *
- * <p>
- * In the event of an erroneous or unmatched argument, the method prints a
- * message and exits the program with code 1.
- *
- * <p>
- * If help options are enabled and one of the arguments matches a help
- * option, then the result of {@link #getHelpMessage getHelpMessage} is
- * printed to the default print stream and the program exits with code 0. If
- * help options are not enabled, they are ignored.
- *
- * @param args argument list
- * @see ArgParser#getDefaultPrintStream
- */
- public void matchAllArgs(String[] args) {
- matchAllArgs(args, 0, EXIT_ON_UNMATCHED | EXIT_ON_ERROR);
- }
-
- /**
- * Matches arguments within an argument list and returns those which were
- * not matched. The matching starts at a location in <code>args</code>
- * specified by <code>idx</code>, and unmatched arguments are returned in a
- * String array.
- *
- * <p>
- * In the event of an erroneous argument, the method either prints a message
- * and exits the program (if {@link #EXIT_ON_ERROR} is set in
- * <code>exitFlags</code>) or terminates the matching and creates a error
- * message that can be retrieved by {@link #getErrorMessage}.
- *
- * <p>
- * In the event of an umatched argument, the method will print a message and
- * exit if {@link #EXIT_ON_UNMATCHED} is set in <code>errorFlags</code>.
- * Otherwise, the unmatched argument will be appended to the returned array
- * of unmatched values, and the matching will continue at the next location.
- *
- * <p>
- * If help options are enabled and one of the arguments matches a help
- * option, then the result of {@link #getHelpMessage getHelpMessage} is
- * printed to the the default print stream and the program exits with code
- * 0. If help options are not enabled, then they will not be matched.
- *
- * @param args argument list
- * @param idx starting location in list
- * @param exitFlags conditions causing the program to exit. Should be an
- * or-ed combintion of {@link #EXIT_ON_ERROR} or
- * {@link #EXIT_ON_UNMATCHED}.
- * @return array of arguments that were not matched, or <code>null</code> if
- * all arguments were successfully matched
- * @see ArgParser#getErrorMessage
- * @see ArgParser#getDefaultPrintStream
- */
- public String[] matchAllArgs(String[] args, int idx, int exitFlags) {
- Vector<String> unmatched = new Vector<String>(10);
-
- while (idx < args.length) {
- try {
- idx = matchArg(args, idx);
- if (unmatchedArg != null) {
- if ((exitFlags & EXIT_ON_UNMATCHED) != 0) {
- printErrorAndExit("Unrecognized argument: "
- + unmatchedArg);
- } else {
- unmatched.add(unmatchedArg);
- }
- }
- } catch (ArgParseException e) {
- if ((exitFlags & EXIT_ON_ERROR) != 0) {
- printErrorAndExit(e.getMessage());
- }
- break;
- }
- }
- if (unmatched.size() == 0) {
- return null;
- } else {
- return (String[]) unmatched.toArray(new String[0]);
- }
- }
-
- /**
- * Matches one option starting at a specified location in an argument list.
- * The method returns the location in the list where the next match should
- * begin.
- *
- * <p>
- * In the event of an erroneous argument, the method throws an
- * {@link argparser.ArgParseException ArgParseException} with an appropriate
- * error message. This error message can also be retrieved using
- * {@link #getErrorMessage getErrorMessage}.
- *
- * <p>
- * In the event of an umatched argument, the method will return idx + 1, and
- * {@link #getUnmatchedArgument getUnmatchedArgument} will return a copy of
- * the unmatched argument. If an argument is matched,
- * {@link #getUnmatchedArgument getUnmatchedArgument} will return
- * <code>null</code>.
- *
- * <p>
- * If help options are enabled and the argument matches a help option, then
- * the result of {@link #getHelpMessage getHelpMessage} is printed to the
- * the default print stream and the program exits with code 0. If help
- * options are not enabled, then they are ignored.
- *
- * @param args argument list
- * @param idx location in list where match should start
- * @return location in list where next match should start
- * @throws ArgParseException if there was an error performing the match
- * (such as improper or insufficient values).
- * @see ArgParser#setDefaultPrintStream
- * @see ArgParser#getHelpOptionsEnabled
- * @see ArgParser#getErrorMessage
- * @see ArgParser#getUnmatchedArgument
- */
- @SuppressWarnings("unchecked")
- public int matchArg(String[] args, int idx) throws ArgParseException {
- unmatchedArg = null;
- setError(null);
- try {
- ObjectHolder ndescHolder = new ObjectHolder();
- Record rec = getRecord(args[idx], ndescHolder);
- if (rec == null || (rec.convertCode == 'h' && !helpOptionsEnabled)) { // didn't
- // match
- unmatchedArg = new String(args[idx]);
- return idx + 1;
- }
- NameDesc ndesc = (NameDesc) ndescHolder.value;
- Object result;
- if (rec.resHolder instanceof Vector) {
- result = createResultHolder(rec);
- } else {
- result = rec.resHolder;
- }
- if (rec.convertCode == 'h') {
- if (helpOptionsEnabled) {
- printStream.println(getHelpMessage());
- System.exit(0);
- } else {
- return idx + 1;
- }
- } else if (rec.convertCode != 'v') {
- if (ndesc.oneWord) {
- rec.scanValue(result, ndesc.name,
- args[idx].substring(ndesc.name.length()), 0);
- } else {
- if (idx + rec.numValues >= args.length) {
- throw new ArgParseException(ndesc.name, "requires "
- + rec.numValues + " value"
- + (rec.numValues > 1 ? "s" : ""));
- }
- for (int k = 0; k < rec.numValues; k++) {
- rec.scanValue(result, ndesc.name, args[++idx], k);
- }
- }
- } else {
- if (rec.resHolder instanceof BooleanHolder) {
- ((BooleanHolder) result).value = rec.vval;
- } else {
- for (int k = 0; k < rec.numValues; k++) {
- ((boolean[]) result)[k] = rec.vval;
- }
- }
- }
- if (rec.resHolder instanceof Vector) {
- ((Vector<Object>) rec.resHolder).add(result);
- }
- } catch (ArgParseException e) {
- setError(e.getMessage());
- throw e;
- }
- return idx + 1;
- }
-
- private String spaceString(int n) {
- StringBuffer sbuf = new StringBuffer(n);
- for (int i = 0; i < n; i++) {
- sbuf.append(' ');
- }
- return sbuf.toString();
- }
-
- // public String getShortHelpMessage ()
- // {
- // String s;
- // Record rec;
- // NameDesc ndesc;
- // int initialIndent = 8;
- // int col = initialIndent;
-
- // if (maxcols <= 0)
- // { maxcols = 80;
- // }
- // if (matchList.size() > 0)
- // { ps.print (spaceString(initialIndent));
- // }
- // for (int i=0; i<matchList.size(); i++)
- // { rec = (Record)matchList.get(i);
- // s = "[";
- // for (ndesc=rec.nameList; ndesc!=null; ndesc=ndesc.next)
- // { s = s + ndesc.name;
- // if (ndesc.oneWord == false)
- // { s = s + " ";
- // }
- // if (ndesc.next != null)
- // { s = s + ",";
- // }
- // }
- // if (rec.convertCode != 'v' && rec.convertCode != 'h')
- // { if (rec.valueDesc != null)
- // { s += rec.valueDesc;
- // }
- // else
- // { s = s + "<" + rec.valTypeName() + ">";
- // if (rec.numValues > 1)
- // { s += "X" + rec.numValues;
- // }
- // }
- // }
- // s = s + "]";
- // /*
- // (col+=s.length()) > (maxcols-1) => we will spill over edge.
- // we use (maxcols-1) because if we go right to the edge
- // (maxcols), we get wrap new line inserted "for us".
- // i != 0 means we print the first entry, no matter
- // how long it is. Subsequent entries are printed
- // full length anyway. */
-
- // if ((col+=s.length()) > (maxcols-1) && i != 0)
- // { col = initialIndent+s.length();
- // ps.print ("\n" + spaceString(initialIndent));
- // }
- // ps.print (s);
- // }
- // if (matchList.size() > 0)
- // { ps.print ('\n');
- // ps.flush();
- // }
- // }
-
- /**
- * Returns a string describing the allowed options in detail.
- *
- * @return help information string.
- */
- public String getHelpMessage() {
- Record rec;
- NameDesc ndesc;
- boolean hasOneWordAlias = false;
- String s;
-
- s = "Usage: " + synopsisString + "\n";
- s += "Options include:\n\n";
- for (int i = 0; i < matchList.size(); i++) {
- String optionInfo = "";
- rec = (Record) matchList.get(i);
- if (rec.convertCode == 'h' && !helpOptionsEnabled) {
- continue;
- }
- for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
- if (ndesc.oneWord) {
- hasOneWordAlias = true;
- break;
- }
- }
- for (ndesc = rec.nameList; ndesc != null; ndesc = ndesc.next) {
- optionInfo += ndesc.name;
- if (hasOneWordAlias && !ndesc.oneWord) {
- optionInfo += " ";
- }
- if (ndesc.next != null) {
- optionInfo += ",";
- }
- }
- if (!hasOneWordAlias) {
- optionInfo += " ";
- }
- if (rec.convertCode != 'v' && rec.convertCode != 'h') {
- if (rec.valueDesc != null) {
- optionInfo += rec.valueDesc;
- } else {
- if (rec.rangeDesc != null) {
- optionInfo += "<" + rec.valTypeName() + " "
- + rec.rangeDesc + ">";
- } else {
- optionInfo += "<" + rec.valTypeName() + ">";
- }
- }
- }
- if (rec.numValues > 1) {
- optionInfo += "X" + rec.numValues;
- }
- s += optionInfo;
- if (rec.helpMsg.length() > 0) {
- int pad = helpIndent - optionInfo.length();
- if (pad < 2) { // s += '\n';
- pad = helpIndent;
- }
- // s += spaceString(pad) + rec.helpMsg;
- s += spaceString(4) + rec.helpMsg;
- }
- s += '\n';
- }
- return s;
- }
-
- /**
- * Returns the parser's error message. This is automatically set whenever an
- * error is encountered in <code>matchArg</code> or
- * <code>matchAllArgs</code>, and is automatically set to <code>null</code>
- * at the beginning of these methods.
- *
- * @return error message
- */
- public String getErrorMessage() {
- return errMsg;
- }
-
- /**
- * Returns the value of an unmatched argument discovered {@link #matchArg
- * matchArg} or {@link #matchAllArgs(String[],int,int) matchAllArgs}. If
- * there was no unmatched argument, <code>null</code> is returned.
- *
- * @return unmatched argument
- */
- public String getUnmatchedArgument() {
- return unmatchedArg;
- }
-}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
index cf01f989..579f0f59 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,17 +18,17 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
- * copy, modify and redistribute is granted, provided that this copyright
- * notice is retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including
- * any implied warranty of merchantability or fitness for a particular
- * use. The author assumes no responsibility for, and shall not be liable
- * for, any special, indirect, or consequential damages, or any damages
- * whatsoever, arising out of or in connection with the use of this
- * software.
- */
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
+ * copy, modify and redistribute is granted, provided that this copyright
+ * notice is retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including
+ * any implied warranty of merchantability or fitness for a particular
+ * use. The author assumes no responsibility for, and shall not be liable
+ * for, any special, indirect, or consequential damages, or any damages
+ * whatsoever, arising out of or in connection with the use of this
+ * software.
+ */
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@@ -37,1246 +36,1537 @@ import java.lang.reflect.Array;
import java.util.Vector;
/**
- * Testing class for the class ArgParser. Executing the <code>main</code> method
- * of this class will perform a suite of tests to help verify correct operation
- * of the parser class.
- *
+ * Testing class for the class ArgParser. Executing the <code>main</code>
+ * method of this class will perform a suite of tests to help verify correct
+ * operation of the parser class.
+ *
* @author John E. Lloyd, Fall 2004
* @see ArgParser
*/
-public class ArgParserTest {
- ArgParser parser;
-
- static final boolean CLOSED = true;
- static final boolean OPEN = false;
-
- static final boolean ONE_WORD = true;
- static final boolean MULTI_WORD = false;
-
- private static void verify(boolean ok, String msg) {
- if (!ok) {
- Throwable e = new Throwable();
- System.out.println("Verification failed:" + msg);
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- private static String[] argsFromString(String s) {
- Vector<String> vec = new Vector<String>(100);
- try {
- ArgParser.stringToArgs(vec, s, /* allowQuotedStings= */false);
- } catch (StringScanException e) {
- e.printStackTrace();
- System.exit(1);
- }
- String[] result = new String[vec.size()];
- for (int i = 0; i < vec.size(); i++) {
- result[i] = (String) vec.get(i);
- }
- return result;
- }
-
- static class RngCheck {
- ArgParser.RangePnt low = null;
- ArgParser.RangePnt high = null;
- int type;
-
- RngCheck(String s) {
- low = new ArgParser.RangePnt(s, CLOSED);
- type = 's';
- }
-
- RngCheck(double d) {
- low = new ArgParser.RangePnt(d, CLOSED);
- type = 'd';
- }
-
- RngCheck(long l) {
- low = new ArgParser.RangePnt(l, CLOSED);
- type = 'l';
- }
-
- RngCheck(boolean b) {
- low = new ArgParser.RangePnt(b, CLOSED);
- type = 'b';
- }
-
- RngCheck(String s1, boolean c1, String s2, boolean c2) {
- low = new ArgParser.RangePnt(s1, c1);
- high = new ArgParser.RangePnt(s2, c2);
- type = 's';
- }
-
- RngCheck(double d1, boolean c1, double d2, boolean c2) {
- low = new ArgParser.RangePnt(d1, c1);
- high = new ArgParser.RangePnt(d2, c2);
- type = 'd';
- }
-
- RngCheck(long l1, boolean c1, long l2, boolean c2) {
- low = new ArgParser.RangePnt(l1, c1);
- high = new ArgParser.RangePnt(l2, c2);
- type = 'l';
- }
-
- void check(ArgParser.RangeAtom ra) {
- verify((ra.low == null) == (low == null), "(ra.low==null)="
- + (ra.low == null) + "(low==null)=" + (low == null));
- verify((ra.high == null) == (high == null), "(ra.high==null)="
- + (ra.high == null) + "(high==null)=" + (high == null));
-
- if (ra.low != null) {
- switch (type) {
- case 'l': {
- verify(ra.low.lval == low.lval, "ra.low=" + ra.low
- + " low=" + low);
- break;
- }
- case 'd': {
- verify(ra.low.dval == low.dval, "ra.low=" + ra.low
- + " low=" + low);
- break;
- }
- case 's': {
- verify(ra.low.sval.equals(low.sval), "ra.low=" + ra.low
- + " low=" + low);
- break;
- }
- case 'b': {
- verify(ra.low.bval == low.bval, "ra.low=" + ra.low
- + " low=" + low);
- break;
- }
- }
- verify(ra.low.closed == low.closed, "ra.low=" + ra.low
- + " low=" + low);
- }
- if (ra.high != null) {
- switch (type) {
- case 'l': {
- verify(ra.high.lval == high.lval, "ra.high=" + ra.high
- + " high=" + high);
- break;
- }
- case 'd': {
- verify(ra.high.dval == high.dval, "ra.high=" + ra.high
- + " high=" + high);
- break;
- }
- case 's': {
- verify(ra.high.sval.equals(high.sval), "ra.high=" + ra.high
- + " high=" + high);
- break;
- }
- case 'b': {
- verify(ra.high.bval == high.bval, "ra.high=" + ra.high
- + " high=" + high);
- break;
- }
- }
- verify(ra.high.closed == high.closed, "ra.high=" + ra.high
- + " high=" + high);
- }
- }
- }
-
- ArgParserTest() {
- parser = new ArgParser("fubar");
- }
-
- static void checkException(Exception e, String errmsg) {
- if (errmsg != null) {
- if (!e.getMessage().equals(errmsg)) {
- System.out.println("Expecting exception '" + errmsg
- + "' but got '" + e.getMessage() + "'");
- e.printStackTrace();
- (new Throwable()).printStackTrace();
- System.exit(1);
- }
- } else {
- System.out.println("Unexpected exception '" + e.getMessage() + "'");
- e.printStackTrace();
- (new Throwable()).printStackTrace();
- System.exit(1);
- }
- }
-
- void checkPrintHelp(String msg) {
- ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
- PrintStream ps = new PrintStream(buf);
- ps.println(parser.getHelpMessage());
- System.out.print(buf.toString());
- }
-
- // void checkGetSynopsis (String msg)
- // {
- // ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
- // PrintStream ps = new PrintStream(buf);
- // parser.printSynopsis (ps, 80);
- // System.out.print (buf.toString());
- // }
-
- void checkAdd(String s, Object resHolder, String errmsg) {
- checkAdd(s, resHolder, 0, 0, null, null, null, errmsg);
- }
-
- void add(String s, Object resHolder) {
- try {
- parser.addOption(s, resHolder);
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
-
- void checkStringArray(String msg, String[] strs, String[] check) {
- boolean dontMatch = false;
- if (strs.length != check.length) {
- dontMatch = true;
- } else {
- for (int i = 0; i < strs.length; i++) {
- if (!strs[i].equals(check[i])) {
- dontMatch = true;
- break;
- }
- }
- }
- if (dontMatch) {
- System.out.println(msg);
- System.out.print("Expected: ");
- for (int i = 0; i < check.length; i++) {
- System.out.print("'" + check[i] + "'");
- if (i < check.length - 1) {
- System.out.print(" ");
- }
- }
- System.out.println("");
- System.out.print("Got: ");
- for (int i = 0; i < strs.length; i++) {
- System.out.print("'" + strs[i] + "'");
- if (i < strs.length - 1) {
- System.out.print(" ");
- }
- }
- System.out.println("");
- System.exit(1);
- }
- }
-
- void checkAdd(String s, Object resHolder, int code, int numValues,
- Object names, RngCheck[] rngCheck, String helpMsg, String errmsg) {
- boolean exceptionThrown = false;
- String[] namelist = null;
- try {
- parser.addOption(s, resHolder);
- } catch (Exception e) {
- exceptionThrown = true;
- checkException(e, errmsg);
- }
- if (names instanceof String) {
- namelist = new String[] { (String) names };
- } else {
- namelist = (String[]) names;
- }
- if (!exceptionThrown) {
- verify(errmsg == null, "Expecting exception " + errmsg);
- ArgParser.Record rec = parser.lastMatchRecord();
- verify(rec.convertCode == code, "code=" + rec.convertCode
- + ", expecting " + code);
- ArgParser.NameDesc nd;
- int i = 0;
- for (nd = rec.firstNameDesc(); nd != null; nd = nd.next) {
- i++;
- }
- verify(i == namelist.length, "numNames=" + i + ", expecting "
- + namelist.length);
- i = 0;
- for (nd = rec.firstNameDesc(); nd != null; nd = nd.next) {
- String ss;
- if (!nd.oneWord) {
- ss = new String(nd.name) + ' ';
- } else {
- ss = nd.name;
- }
- verify(ss.equals(namelist[i]), "have name '" + ss
- + "', expecting '" + namelist[i] + "'");
- i++;
- }
- ArgParser.RangeAtom ra;
- i = 0;
- for (ra = rec.firstRangeAtom(); ra != null; ra = ra.next) {
- i++;
- }
- int expectedRangeNum = 0;
- if (rngCheck != null) {
- expectedRangeNum = rngCheck.length;
- }
- verify(i == expectedRangeNum, "numRangeAtoms=" + i + ", expecting "
- + expectedRangeNum);
- i = 0;
- for (ra = rec.firstRangeAtom(); ra != null; ra = ra.next) {
- rngCheck[i++].check(ra);
- }
- verify(rec.helpMsg.equals(helpMsg), "helpMsg=" + rec.helpMsg
- + ", expecting " + helpMsg);
- verify(rec.numValues == numValues, "numValues=" + rec.numValues
- + ", expecting " + numValues);
- }
- }
-
- double getDoubleValue(Object obj, int k) {
- if (obj instanceof DoubleHolder) {
- return ((DoubleHolder) obj).value;
- } else if (obj instanceof FloatHolder) {
- return ((FloatHolder) obj).value;
- } else if (obj instanceof double[]) {
- return ((double[]) obj)[k];
- } else if (obj instanceof float[]) {
- return ((float[]) obj)[k];
- } else {
- verify(false, "object doesn't contain double values");
- return 0;
- }
- }
-
- long getLongValue(Object obj, int k) {
- if (obj instanceof LongHolder) {
- return ((LongHolder) obj).value;
- } else if (obj instanceof IntHolder) {
- return ((IntHolder) obj).value;
- } else if (obj instanceof long[]) {
- return ((long[]) obj)[k];
- } else if (obj instanceof int[]) {
- return ((int[]) obj)[k];
- } else {
- verify(false, "object doesn't contain long values");
- return 0;
- }
- }
-
- String getStringValue(Object obj, int k) {
- if (obj instanceof StringHolder) {
- return ((StringHolder) obj).value;
- } else if (obj instanceof String[]) {
- return ((String[]) obj)[k];
- } else {
- verify(false, "object doesn't contain String values");
- return null;
- }
- }
-
- boolean getBooleanValue(Object obj, int k) {
- if (obj instanceof BooleanHolder) {
- return ((BooleanHolder) obj).value;
- } else if (obj instanceof boolean[]) {
- return ((boolean[]) obj)[k];
- } else {
- verify(false, "object doesn't contain boolean values");
- return false;
- }
- }
-
- char getCharValue(Object obj, int k) {
- if (obj instanceof CharHolder) {
- return ((CharHolder) obj).value;
- } else if (obj instanceof char[]) {
- return ((char[]) obj)[k];
- } else {
- verify(false, "object doesn't contain char values");
- return 0;
- }
- }
-
- static class MErr {
- int code;
- String valStr;
-
- MErr(int code, String valStr) {
- this.code = code;
- this.valStr = valStr;
- }
- }
-
- static class MTest {
- String args;
- Object result;
- int resultIdx;
-
- MTest(String args, Object result) {
- this(args, result, -1);
- }
-
- MTest(String args, Object result, int resultIdx) {
- this.args = args;
- this.result = result;
- this.resultIdx = resultIdx;
- }
- };
-
- void checkMatch(String args[], int idx, String errMsg) {
- getMatchResult(args, idx, -1, errMsg, -1);
- }
-
- void checkMatch(String args[], int idx, int cnt, long check, int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- long result = getLongValue(rholder, 0);
- verify(result == check, "result " + result + " vs. " + check);
- }
-
- void checkMatch(String args[], int idx, int cnt, double check, int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- double result = getDoubleValue(rholder, 0);
- verify(result == check, "result " + result + " vs. " + check);
- }
-
- void checkMatch(String args[], int idx, int cnt, String check, int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- String result = getStringValue(rholder, 0);
- verify(result.equals(check), "result " + result + " vs. " + check);
- }
-
- void checkMatch(String args[], int idx, int cnt, boolean check,
- int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- boolean result = getBooleanValue(rholder, 0);
- verify(result == check, "result " + result + " vs. " + check);
- }
-
- void checkMatch(String args[], int idx, int cnt, char check, int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- char result = getCharValue(rholder, 0);
- verify(result == check, "result " + result + " vs. " + check);
- }
-
- void checkMatch(String args[], int idx, int cnt, Object checkArray,
- int resultIdx) {
- Object rholder = getMatchResult(args, idx, cnt, null, resultIdx);
- if (!checkArray.getClass().isArray()) {
- verify(false, "check is not an array");
- }
- for (int i = 0; i < Array.getLength(checkArray); i++) {
- if (checkArray instanceof long[]) {
- long result = getLongValue(rholder, i);
- long check = ((long[]) checkArray)[i];
- verify(result == check, "result [" + i + "] " + result
- + " vs. " + check);
- } else if (checkArray instanceof double[]) {
- double result = getDoubleValue(rholder, i);
- double check = ((double[]) checkArray)[i];
- verify(result == check, "result [" + i + "] " + result
- + " vs. " + check);
- } else if (checkArray instanceof String[]) {
- String result = getStringValue(rholder, i);
- String check = ((String[]) checkArray)[i];
- verify(result.equals(check), "result [" + i + "] " + result
- + " vs. " + check);
- } else if (checkArray instanceof boolean[]) {
- boolean result = getBooleanValue(rholder, i);
- boolean check = ((boolean[]) checkArray)[i];
- verify(result == check, "result [" + i + "] " + result
- + " vs. " + check);
- } else if (checkArray instanceof char[]) {
- char result = getCharValue(rholder, i);
- char check = ((char[]) checkArray)[i];
- verify(result == check, "result [" + i + "] " + result
- + " vs. " + check);
- } else {
- verify(false, "unknown type for checkArray");
- }
- }
- }
-
- void checkMatch(MTest test, boolean oneWord) {
- String[] argv;
- if (oneWord) {
- argv = new String[1];
- argv[0] = test.args;
- } else {
- argv = argsFromString(test.args);
- }
- if (test.result instanceof Long) {
- checkMatch(argv, 0, argv.length, ((Long) test.result).longValue(),
- test.resultIdx);
- } else if (test.result instanceof Double) {
- checkMatch(argv, 0, argv.length,
- ((Double) test.result).doubleValue(), test.resultIdx);
- } else if (test.result instanceof String) {
- checkMatch(argv, 0, argv.length, (String) test.result,
- test.resultIdx);
- } else if (test.result instanceof Boolean) {
- checkMatch(argv, 0, argv.length,
- ((Boolean) test.result).booleanValue(), test.resultIdx);
- } else if (test.result instanceof Character) {
- checkMatch(argv, 0, argv.length,
- ((Character) test.result).charValue(), test.resultIdx);
- } else if (test.result.getClass().isArray()) {
- checkMatch(argv, 0, argv.length, test.result, test.resultIdx);
- } else if (test.result instanceof MErr) {
- MErr err = (MErr) test.result;
- String argname = parser.getOptionName(argv[0]);
- String msg = "";
-
- switch (err.code) {
- case 'c': {
- msg = "requires a contiguous value";
- break;
- }
- case 'm': {
- msg = "malformed " + parser.getOptionTypeName(argv[0]) + " '"
- + err.valStr + "'";
- break;
- }
- case 'r': {
- msg = "value '" + err.valStr + "' not in range "
- + parser.getOptionRangeDesc(argv[0]);
- break;
- }
- case 'v': {
- msg = "requires " + err.valStr + " values";
- break;
- }
- }
- checkMatch(argv, 0, argname + ": " + msg);
- } else {
- verify(false, "Unknown result type");
- }
- }
-
- void checkMatches(MTest[] tests, boolean oneWord) {
- for (int i = 0; i < tests.length; i++) {
- checkMatch(tests[i], oneWord);
- }
- }
-
- Object getMatchResult(String args[], int idx, int cnt, String errMsg,
- int resultIdx) {
- boolean exceptionThrown = false;
- int k = 0;
- try {
- k = parser.matchArg(args, idx);
- } catch (Exception e) {
- exceptionThrown = true;
- checkException(e, errMsg);
- }
- if (!exceptionThrown) {
- verify(k == idx + cnt, "Expecting result index " + (idx + cnt)
- + ", got " + k);
- Object result = parser.getResultHolder(args[0]);
- if (resultIdx >= 0) {
- verify(result instanceof Vector,
- "Expecting result to be stored in a vector");
- Vector<?> vec = (Vector<?>) result;
- verify(vec.size() == resultIdx + 1,
- "Expecting result vector size " + (resultIdx + 1));
- return vec.get(resultIdx);
- } else {
- return result;
- }
- } else {
- return null;
- }
- }
-
- /**
- * Runs a set of tests to verify correct operation of the ArgParser class.
- * If all the tests run correctly, the program prints the message
- * <code>Passed</code> and terminates. Otherwise, diagnostic information is
- * printed at the first point of failure.
- */
- public static void main(String[] args) {
- ArgParserTest test = new ArgParserTest();
-
- BooleanHolder bh = new BooleanHolder();
- boolean[] b3 = new boolean[3];
- CharHolder ch = new CharHolder();
- char[] c3 = new char[3];
- IntHolder ih = new IntHolder();
- int[] i3 = new int[3];
- LongHolder lh = new LongHolder();
- long[] l3 = new long[3];
- FloatHolder fh = new FloatHolder();
- float[] f3 = new float[3];
- DoubleHolder dh = new DoubleHolder();
- double[] d3 = new double[3];
- StringHolder sh = new StringHolder();
- String[] s3 = new String[3];
-
- test.checkAdd(
- "-foo %i{[0,10)}X3 #sets the value of foo",
- // 0123456789012345
- i3, 'i', 3, new String[] { "-foo " },
- new RngCheck[] { new RngCheck(0, CLOSED, 10, OPEN) },
- "sets the value of foo", null);
-
- test.checkAdd("-arg1,,", null, "Null option name given");
- test.checkAdd("-arg1,,goo %f ", null, "Null option name given");
- test.checkAdd(" ", null, "Null option name given");
- test.checkAdd("", null, "Null option name given");
- test.checkAdd(" %v", null, "Null option name given");
- test.checkAdd("-foo ", null, "No conversion character given");
- test.checkAdd("-foo %", null, "No conversion character given");
- test.checkAdd("foo, aaa bbb ", null, "Names not separated by ','");
- test.checkAdd(" foo aaa %d", null, "Names not separated by ','");
- test.checkAdd("-arg1,-b,", null, "Null option name given");
- test.checkAdd("-arg1,-b", null, "No conversion character given");
- test.checkAdd("-arg1 ", null, "No conversion character given");
- test.checkAdd("-arg1, %v", null, "Null option name given");
- test.checkAdd("-arg1,%v", null, "Null option name given");
- test.checkAdd("-foo %V", null,
- "Conversion code 'V' not one of 'iodxcbfsvh'");
- test.checkAdd("-h %hX5", null, "Multipliers not supported for %h");
- test.checkAdd("-h %h{}", null, "Ranges not supported for %h");
- test.checkAdd("-help, -h %h #here is how we help you", null, 'h', 1,
- new String[] { "-help ", "-h " }, null,
- "here is how we help you", null);
-
- test.checkAdd("-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test", l3, 'd', 1,
- new String[] { "-arg1 ", "-arg2=" }, new RngCheck[] {
- new RngCheck(0), new RngCheck(3),
- new RngCheck(7, OPEN, 16, CLOSED), }, "x3 test", null);
-
- test.checkAdd("bbb,ccc%x{[1,2]} #X3 x3 test", l3, 'x', 1, new String[] {
- "bbb", "ccc" }, new RngCheck[] { new RngCheck(1, CLOSED, 2,
- CLOSED), }, "X3 x3 test", null);
-
- test.checkAdd(" bbb ,ccc, ddd ,e , f=%bX1 #x3 test", b3, 'b', 1,
- new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" }, null,
- "x3 test", null);
-
- test.checkAdd(" bbb ,ccc, ddd ,e , f= %bX3 #x3 test", b3, 'b', 3,
- new String[] { "bbb ", "ccc ", "ddd ", "e ", "f= " }, null,
- "x3 test", null);
-
- test.checkAdd(
- "-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar",
- sh, 's', 1, new String[] { "-b ", "--bar " }, new RngCheck[] {
- new RngCheck("jerry", OPEN, "john", CLOSED),
- new RngCheck("fred"), new RngCheck("harry") },
- "sets bar", null);
-
- test.checkAdd("-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ", dh, 'f', 1,
- new String[] { "-c ", "coven" }, new RngCheck[] {
- new RngCheck(0.0), new RngCheck(9.0),
- new RngCheck(5.0, CLOSED, 6.0, OPEN),
- new RngCheck(-9.1, CLOSED, 10.2, CLOSED) }, "", null);
-
- test.checkAdd("-b %b #a boolean value ", bh, 'b', 1,
- new String[] { "-b " }, new RngCheck[] {}, "a boolean value ",
- null);
-
- test.checkAdd("-a %i", ih, 'i', 1, "-a ", null, "", null);
- test.checkAdd("-a %o", lh, 'o', 1, "-a ", null, "", null);
- test.checkAdd("-a %d", i3, 'd', 1, "-a ", null, "", null);
- test.checkAdd("-a %x", l3, 'x', 1, "-a ", null, "", null);
- test.checkAdd("-a %c", ch, 'c', 1, "-a ", null, "", null);
- test.checkAdd("-a %c", c3, 'c', 1, "-a ", null, "", null);
- test.checkAdd("-a %v", bh, 'v', 1, "-a ", null, "", null);
- test.checkAdd("-a %b", b3, 'b', 1, "-a ", null, "", null);
- test.checkAdd("-a %f", fh, 'f', 1, "-a ", null, "", null);
- test.checkAdd("-a %f", f3, 'f', 1, "-a ", null, "", null);
- test.checkAdd("-a %f", dh, 'f', 1, "-a ", null, "", null);
- test.checkAdd("-a %f", d3, 'f', 1, "-a ", null, "", null);
-
- test.checkAdd("-a %i", fh, 'i', 1, "-a ", null, "",
- "Invalid result holder for %i");
- test.checkAdd("-a %c", i3, 'c', 1, "-a ", null, "",
- "Invalid result holder for %c");
- test.checkAdd("-a %v", d3, 'v', 1, "-a ", null, "",
- "Invalid result holder for %v");
- test.checkAdd("-a %f", sh, 'f', 1, "-a ", null, "",
- "Invalid result holder for %f");
- test.checkAdd("-a %s", l3, 's', 1, "-a ", null, "",
- "Invalid result holder for %s");
-
- test.checkAdd("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null);
- test.checkAdd("-foo%i{}", ih, 'i', 1, "-foo", null, "", null);
- test.checkAdd("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null);
- test.checkAdd("-foo%i{ }}", ih, "Illegal character(s), expecting '#'");
- test.checkAdd("-foo%i{ ", ih, "Unterminated range specification");
- test.checkAdd("-foo%i{", ih, "Unterminated range specification");
- test.checkAdd("-foo%i{0,9", ih, "Unterminated range specification");
- test.checkAdd("-foo%i{1,2,3)", ih, "Unterminated range specification");
-
- test.checkAdd("-b %f{0.9}", fh, 'f', 1, "-b ",
- new RngCheck[] { new RngCheck(0.9) }, "", null);
- test.checkAdd("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ",
- new RngCheck[] { new RngCheck(0.9), new RngCheck(7.0),
- new RngCheck(-0.5), new RngCheck(-4.0),
- new RngCheck(6.0) }, "", null);
- test.checkAdd("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }", fh, 'f',
- 1, "-b ", new RngCheck[] {
- new RngCheck(0.9, CLOSED, 7.0, OPEN),
- new RngCheck(-4.0, OPEN, -.5, OPEN),
- new RngCheck(6.0, CLOSED, 9.0, CLOSED),
- new RngCheck(10.0, OPEN, 13.4, CLOSED), }, "", null);
- test.checkAdd("-b %f{(8 9]}", fh,
- "Missing ',' in subrange specification");
- test.checkAdd("-b %f{(8,9,]}", fh, "Unterminated subrange");
- test.checkAdd("-b %f{(8,9 ,]}", fh, "Unterminated subrange");
- test.checkAdd("-b %f{(8,9 8]}", fh, "Unterminated subrange");
- test.checkAdd("-b %f{8 9}", fh, "Range spec: ',' or '}' expected");
- test.checkAdd("-b %f{8 *}", fh, "Range spec: ',' or '}' expected");
-
- test.checkAdd("-b %f{8y}", fh, "Range spec: ',' or '}' expected");
- test.checkAdd("-b %f{.}", fh, "Malformed float '.}' in range spec");
- test.checkAdd("-b %f{1.0e}", fh,
- "Malformed float '1.0e}' in range spec");
- test.checkAdd("-b %f{[*]}", fh, "Malformed float '*' in range spec");
- test.checkAdd("-b %f{1.2e5t}", fh, "Range spec: ',' or '}' expected");
-
- test.checkAdd("-b %i{8}", ih, 'i', 1, "-b ",
- new RngCheck[] { new RngCheck(8) }, "", null);
- test.checkAdd("-b %i{8, 9,10 }", ih, 'i', 1, "-b ", new RngCheck[] {
- new RngCheck(8), new RngCheck(9), new RngCheck(10) }, "", null);
- test.checkAdd("-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }", ih, 'i', 1,
- "-b ", new RngCheck[] { new RngCheck(8),
- new RngCheck(-9, CLOSED, 10, OPEN),
- new RngCheck(-17, CLOSED, 15, CLOSED),
- new RngCheck(-33, OPEN, 2, OPEN),
- new RngCheck(8, OPEN, 9, CLOSED), }, "", null);
- test.checkAdd("-b %i{8.7}", ih, "Range spec: ',' or '}' expected");
- test.checkAdd("-b %i{6,[*]}", ih, "Malformed integer '*' in range spec");
- test.checkAdd("-b %i{g76}", ih, "Malformed integer 'g' in range spec");
-
- test.checkAdd("-b %s{foobar}", sh, 's', 1, "-b ",
- new RngCheck[] { new RngCheck("foobar") }, "", null);
- test.checkAdd("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ",
- new RngCheck[] { new RngCheck("foobar"), new RngCheck("0x233"),
- new RngCheck(" ") }, "", null);
- test.checkAdd("-b %s{foobar,(bb,aa], [\"01\",02]}", sh, 's', 1, "-b ",
- new RngCheck[] { new RngCheck("foobar"),
- new RngCheck("aa", CLOSED, "bb", OPEN),
- new RngCheck("01", CLOSED, "02", CLOSED), }, "", null);
-
- test.checkAdd("-b %c{'a'}", ch, 'c', 1, "-b ",
- new RngCheck[] { new RngCheck('a') }, "", null);
- test.checkAdd("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ",
- new RngCheck[] { new RngCheck('\n'), new RngCheck('\002'),
- new RngCheck('B') }, "", null);
- test.checkAdd("-b %c{'q',('g','a'], ['\t','\\003']}", ch, 'c', 1,
- "-b ", new RngCheck[] { new RngCheck('q'),
- new RngCheck('a', CLOSED, 'g', OPEN),
- new RngCheck('\003', CLOSED, '\t', CLOSED), }, "", null);
-
- test.checkAdd("-b %b{true}X2", b3, 'b', 2, "-b ",
- new RngCheck[] { new RngCheck(true) }, "", null);
- test.checkAdd("-b %b{ true , false, true }", bh, 'b', 1, "-b ",
- new RngCheck[] { new RngCheck(true), new RngCheck(false),
- new RngCheck(true) }, "", null);
- test.checkAdd("-b %v{true,[true,false)}", bh,
- "Sub ranges not supported for %b or %v");
- test.checkAdd("-b %v{true,[]}", bh,
- "Sub ranges not supported for %b or %v");
- test.checkAdd("-b %b{tru}", bh,
- "Malformed boolean 'tru}' in range spec");
-
- test.checkAdd("-b %iX2", i3, 'i', 2, "-b ", null, "", null);
- test.checkAdd("-b %vX3", b3, 'v', 3, "-b ", null, "", null);
- test.checkAdd("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null);
-
- test.checkAdd("-b=%iX2", i3, 'i', 2, "-b", null, "",
- "Multiplier value incompatible with one word option -b=");
- test.checkAdd("-b %iX0", i3, 'i', 0, "-b ", null, "",
- "Value multiplier number must be > 0");
- test.checkAdd("-b %iX-6", i3, 'i', 0, "-b ", null, "",
- "Value multiplier number must be > 0");
- test.checkAdd("-b %iXy", i3, 'i', 0, "-b ", null, "",
- "Malformed value multiplier");
- test.checkAdd("-b %iX4", i3, 'i', 4, "-b ", null, "",
- "Result holder array must have a length >= 4");
- test.checkAdd("-b %iX4", ih, 'i', 4, "-b ", null, "",
- "Multiplier requires result holder to be an array of length >= 4");
-
- test.checkAdd("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null);
- test.checkAdd("-b %i #[}X4", ih, 'i', 1, "-b ", null, "[}X4", null);
-
- // test.checkPrintHelp("");
- // test.checkPrintUsage("");
-
- test = new ArgParserTest();
-
- test.checkAdd(
- "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg",
- ih, 'i', 1, "-intarg ", new RngCheck[] { new RngCheck(1),
- new RngCheck(2), new RngCheck(9, OPEN, 18, CLOSED),
- new RngCheck(22, CLOSED, 27, CLOSED),
- new RngCheck(33, CLOSED, 38, OPEN),
- new RngCheck(45, OPEN, 48, OPEN), }, "test int arg",
- null);
-
- MTest[] tests;
-
- tests = new MTest[] { new MTest("-intarg 1", new Long(1)),
- new MTest("-intarg 3", new MErr('r', "3")),
- new MTest("-intarg 9", new MErr('r', "9")),
- new MTest("-intarg 11", new Long(11)),
- new MTest("-intarg 18", new Long(18)),
- new MTest("-intarg 22", new Long(22)),
- new MTest("-intarg 25", new Long(25)),
- new MTest("-intarg 27", new Long(27)),
- new MTest("-intarg 33", new Long(33)),
- new MTest("-intarg 35", new Long(35)),
- new MTest("-intarg 38", new MErr('r', "38")),
- new MTest("-intarg 45", new MErr('r', "45")),
- new MTest("-intarg 46", new Long(46)),
- new MTest("-intarg 48", new MErr('r', "48")),
- new MTest("-intarg 100", new MErr('r', "100")),
- new MTest("-intarg 0xbeef", new MErr('r', "0xbeef")),
- new MTest("-intarg 0x2f", new Long(0x2f)),
- new MTest("-intarg 041", new Long(041)), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd(
- "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg",
- dh, 'f', 1, "-farg ", new RngCheck[] { new RngCheck(1.0),
- new RngCheck(2.0),
- new RngCheck(9.0, OPEN, 18.0, CLOSED),
- new RngCheck(22.0, CLOSED, 27.0, CLOSED),
- new RngCheck(33.0, CLOSED, 38.0, OPEN),
- new RngCheck(45.0, OPEN, 48.0, OPEN), },
- "test float arg", null);
-
- tests = new MTest[] { new MTest("-farg 1", new Double(1)),
- new MTest("-farg 3", new MErr('r', "3")),
- new MTest("-farg 9", new MErr('r', "9")),
- new MTest("-farg 9.0001", new Double(9.0001)),
- new MTest("-farg 11", new Double(11)),
- new MTest("-farg 18", new Double(18)),
- new MTest("-farg 22", new Double(22)),
- new MTest("-farg 25", new Double(25)),
- new MTest("-farg 27", new Double(27)),
- new MTest("-farg 33", new Double(33)),
- new MTest("-farg 35", new Double(35)),
- new MTest("-farg 37.9999", new Double(37.9999)),
- new MTest("-farg 38", new MErr('r', "38")),
- new MTest("-farg 45", new MErr('r', "45")),
- new MTest("-farg 45.0001", new Double(45.0001)),
- new MTest("-farg 46", new Double(46)),
- new MTest("-farg 47.9999", new Double(47.9999)),
- new MTest("-farg 48", new MErr('r', "48")),
- new MTest("-farg 100", new MErr('r', "100")),
- new MTest("-farg 0", new MErr('r', "0")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd(
- "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg",
- s3, 's', 1, "-sarg ", new RngCheck[] { new RngCheck("1"),
- new RngCheck("2"),
- new RngCheck("AA", OPEN, "AZ", CLOSED),
- new RngCheck("BB", CLOSED, "BX", CLOSED),
- new RngCheck("C3", CLOSED, "C8", OPEN),
- new RngCheck("d5", OPEN, "d8", OPEN), },
- "test string arg", null);
-
- tests = new MTest[] { new MTest("-sarg 1", "1"),
- new MTest("-sarg 3", new MErr('r', "3")),
- new MTest("-sarg AA", new MErr('r', "AA")),
- new MTest("-sarg AM", "AM"), new MTest("-sarg AZ", "AZ"),
- new MTest("-sarg BB", "BB"), new MTest("-sarg BL", "BL"),
- new MTest("-sarg BX", "BX"), new MTest("-sarg C3", "C3"),
- new MTest("-sarg C6", "C6"),
- new MTest("-sarg C8", new MErr('r', "C8")),
- new MTest("-sarg d5", new MErr('r', "d5")),
- new MTest("-sarg d6", "d6"),
- new MTest("-sarg d8", new MErr('r', "d8")),
- new MTest("-sarg zzz", new MErr('r', "zzz")),
- new MTest("-sarg 0", new MErr('r', "0")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test = new ArgParserTest();
-
- test.checkAdd("-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}",
- c3, 'c', 1, "-carg ", new RngCheck[] { new RngCheck('1'),
- new RngCheck('2'),
- new RngCheck('a', OPEN, 'z', CLOSED),
- new RngCheck('A', CLOSED, 'Z', CLOSED),
- new RngCheck('\001', CLOSED, '\007', OPEN),
- new RngCheck('4', OPEN, '8', OPEN), }, "", null);
-
- tests = new MTest[] { new MTest("-carg 1", new Character('1')),
- new MTest("-carg 3", new MErr('r', "3")),
- new MTest("-carg a", new MErr('r', "a")),
- new MTest("-carg m", new Character('m')),
- new MTest("-carg z", new Character('z')),
- new MTest("-carg A", new Character('A')),
- new MTest("-carg 'L'", new Character('L')),
- new MTest("-carg 'Z'", new Character('Z')),
- new MTest("-carg \\001", new Character('\001')),
- new MTest("-carg \\005", new Character('\005')),
- new MTest("-carg '\\007'", new MErr('r', "'\\007'")),
- new MTest("-carg '4'", new MErr('r', "'4'")),
- new MTest("-carg 6", new Character('6')),
- new MTest("-carg 8", new MErr('r', "8")),
- new MTest("-carg '\\012'", new MErr('r', "'\\012'")),
- new MTest("-carg 0", new MErr('r', "0")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=",
- new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "",
- null);
-
- tests = new MTest[] { new MTest("-foo=-51", new MErr('r', "-51")),
- new MTest("-foo=-0x32", new Long(-0x32)),
- new MTest("-foo=-0x33", new MErr('r', "-0x33")),
- new MTest("-foo=-0777", new MErr('r', "-0777")),
- new MTest("-foo=-07", new Long(-07)),
- new MTest("-foo=0", new Long(0)),
- new MTest("-foo=100", new Long(100)),
- new MTest("-foo=0x5e", new Long(0x5e)),
- new MTest("-foo=066", new Long(066)),
- new MTest("-foo=06677", new MErr('r', "06677")),
- new MTest("-foo=0xbeef", new MErr('r', "0xbeef")),
- new MTest("-foo=foo", new MErr('m', "foo")),
- new MTest("-foo=-51d", new MErr('m', "-51d")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null);
- tests = new MTest[] { new MTest("-foo2=-51", new Long(-51)),
- new MTest("-foo2=-0x33", new Long(-0x33)),
- new MTest("-foo2=-0777", new Long(-0777)),
- new MTest("-foo2=06677", new Long(06677)),
- new MTest("-foo2=0xbeef", new Long(0xbeef)),
- new MTest("-foo2=foo", new MErr('m', "foo")),
- new MTest("-foo2=-51d", new MErr('m', "-51d")),
- new MTest("-foo2=-51", new Long(-51)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-foo3 -51 678 0x45", new long[] { -51, 678, 0x45 }),
- new MTest("-foo3 55 16f 55", new MErr('m', "16f")),
- new MTest("-foo3 55 16", new MErr('v', "3")), };
- test.checkMatches(tests, MULTI_WORD);
-
- Vector<String> vec = new Vector<String>(100);
-
- test.checkAdd("-foov3 %iX3", vec, 'i', 3, "-foov3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-foov3 -1 2 4", new long[] { -1, 2, 4 }, 0),
- new MTest("-foov3 10 3 9", new long[] { 10, 3, 9 }, 1),
- new MTest("-foov3 123 1 0", new long[] { 123, 1, 0 }, 2), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
- test.checkAdd("-foov %i", vec, 'i', 1, "-foov ", null, "", null);
- tests = new MTest[] { new MTest("-foov 11", new Long(11), 0),
- new MTest("-foov 12", new Long(12), 1),
- new MTest("-foov 13", new Long(13), 2), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ",
- new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "",
- null);
- tests = new MTest[] {
- new MTest("-foo4 -49 78", new long[] { -49, 78 }),
- new MTest("-foo4 -48 102", new MErr('r', "102")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=",
- new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "",
- null);
-
- tests = new MTest[] { new MTest("-oct=-063", new MErr('r', "-063")),
- new MTest("-oct=-0x32", new MErr('m', "-0x32")),
- new MTest("-oct=-0777", new MErr('r', "-0777")),
- new MTest("-oct=-07", new Long(-07)),
- new MTest("-oct=0", new Long(0)),
- new MTest("-oct=100", new Long(64)),
- new MTest("-oct=0xae", new MErr('m', "0xae")),
- new MTest("-oct=66", new Long(066)),
- new MTest("-oct=06677", new MErr('r', "06677")),
- new MTest("-oct=0xbeef", new MErr('m', "0xbeef")),
- new MTest("-oct=foo", new MErr('m', "foo")),
- new MTest("-oct=-51d", new MErr('m', "-51d")),
- new MTest("-oct=78", new MErr('m', "78")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null);
- tests = new MTest[] { new MTest("-oct2=-063", new Long(-063)),
- new MTest("-oct2=-0777", new Long(-0777)),
- new MTest("-oct2=06677", new Long(06677)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=",
- new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "",
- null);
-
- tests = new MTest[] { new MTest("-dec=-063", new MErr('r', "-063")),
- new MTest("-dec=-0x32", new MErr('m', "-0x32")),
- new MTest("-dec=-0777", new MErr('r', "-0777")),
- new MTest("-dec=-07", new Long(-07)),
- new MTest("-dec=0", new Long(0)),
- new MTest("-dec=100", new Long(100)),
- new MTest("-dec=0xae", new MErr('m', "0xae")),
- new MTest("-dec=66", new Long(66)),
- new MTest("-dec=06677", new MErr('r', "06677")),
- new MTest("-dec=0xbeef", new MErr('m', "0xbeef")),
- new MTest("-dec=foo", new MErr('m', "foo")),
- new MTest("-dec=-51d", new MErr('m', "-51d")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null);
- tests = new MTest[] { new MTest("-dec2=-063", new Long(-63)),
- new MTest("-dec2=-0777", new Long(-777)),
- new MTest("-dec2=06677", new Long(6677)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=",
- new RngCheck[] { new RngCheck(-50, CLOSED, 100, CLOSED), }, "",
- null);
-
- tests = new MTest[] { new MTest("-hex=-06", new Long(-0x6)),
- new MTest("-hex=-0x3g2", new MErr('m', "-0x3g2")),
- new MTest("-hex=-0777", new MErr('r', "-0777")),
- new MTest("-hex=-017", new Long(-0x17)),
- new MTest("-hex=0", new Long(0)),
- new MTest("-hex=64", new Long(0x64)),
- new MTest("-hex=5e", new Long(0x5e)),
- new MTest("-hex=66", new MErr('r', "66")),
- new MTest("-hex=06677", new MErr('r', "06677")),
- new MTest("-hex=0xbeef", new MErr('m', "0xbeef")),
- new MTest("-hex=foo", new MErr('m', "foo")),
- new MTest("-hex=-51d", new MErr('r', "-51d")),
- new MTest("-hex=-51g", new MErr('m', "-51g")),
- new MTest("-hex=", new MErr('c', "")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null);
- tests = new MTest[] { new MTest("-hex2=-0777", new Long(-0x777)),
- new MTest("-hex2=66", new Long(0x66)),
- new MTest("-hex2=06677", new Long(0x6677)),
- new MTest("-hex2=-51d", new Long(-0x51d)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-char=%c{['b','m']}", ch, 'c', 1, "-char=",
- new RngCheck[] { new RngCheck('b', CLOSED, 'm', CLOSED), }, "",
- null);
-
- tests = new MTest[] { new MTest("-char=a", new MErr('r', "a")),
- new MTest("-char=b", new Character('b')),
- new MTest("-char='b'", new Character('b')),
- new MTest("-char='\142'", new Character('b')),
- new MTest("-char='\141'", new MErr('r', "'\141'")),
- new MTest("-char=\142", new Character('b')),
- new MTest("-char=\141", new MErr('r', "\141")),
- new MTest("-char=m", new Character('m')),
- new MTest("-char=z", new MErr('r', "z")),
- new MTest("-char=bb", new MErr('m', "bb")),
- new MTest("-char='b", new MErr('m', "'b")),
- new MTest("-char='", new MErr('m', "'")),
- new MTest("-char=a'", new MErr('m', "a'")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-char2=%c", ch, 'c', 1, "-char2=", null, "", null);
- tests = new MTest[] { new MTest("-char2=a", new Character('a')),
- new MTest("-char2='\141'", new Character('\141')),
- new MTest("-char2=\141", new Character('\141')),
- new MTest("-char2=z", new Character('z')), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-charv3 %cX3", vec, 'c', 3, "-charv3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-charv3 a b c", new char[] { 'a', 'b', 'c' }, 0),
- new MTest("-charv3 'g' f '\\n'", new char[] { 'g', 'f', '\n' },
- 1),
- new MTest("-charv3 1 \001 3", new char[] { '1', '\001', '3' },
- 2), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
- test.checkAdd("-charv=%c", vec, 'c', 1, "-charv=", null, "", null);
- tests = new MTest[] { new MTest("-charv=d", new Character('d'), 0),
- new MTest("-charv='g'", new Character('g'), 1),
- new MTest("-charv=\111", new Character('\111'), 2), };
- vec.clear();
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-bool=%b{true}", bh, 'b', 1, "-bool=",
- new RngCheck[] { new RngCheck(true), }, "", null);
-
- tests = new MTest[] { new MTest("-bool=true", new Boolean(true)),
- new MTest("-bool=false", new MErr('r', "false")),
- new MTest("-bool=fals", new MErr('m', "fals")),
- new MTest("-bool=falsem", new MErr('m', "falsem")),
- new MTest("-bool=truex", new MErr('m', "truex")),
- new MTest("-bool=foo", new MErr('m', "foo")),
- new MTest("-bool=1", new MErr('m', "1")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-boo2=%b{true,false}", bh, 'b', 1, "-boo2=",
- new RngCheck[] { new RngCheck(true), new RngCheck(false), },
- "", null);
-
- tests = new MTest[] { new MTest("-boo2=true", new Boolean(true)),
- new MTest("-boo2=false", new Boolean(false)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null);
- tests = new MTest[] { new MTest("-boo3=true", new Boolean(true)),
- new MTest("-boo3=false", new Boolean(false)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-boo3 true false true", new boolean[] { true, false,
- true }),
- new MTest("-boo3 true fals true", new MErr('m', "fals")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-boov3 %bX3", vec, 'b', 3, "-boov3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-boov3 true true false", new boolean[] { true, true,
- false }, 0),
- new MTest("-boov3 false false true", new boolean[] { false,
- false, true }, 1), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
- test.checkAdd("-boov %b", vec, 'b', 1, "-boov ", null, "", null);
- tests = new MTest[] { new MTest("-boov true", new Boolean(true), 0),
- new MTest("-boov false", new Boolean(false), 1),
- new MTest("-boov true", new Boolean(true), 2), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null);
- tests = new MTest[] { new MTest("-v3", new boolean[] { true, true }), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-vf %v{false,true}X2", b3, 'v', 2, "-vf ",
- new RngCheck[] { new RngCheck(false), new RngCheck(true), },
- "", null);
- tests = new MTest[] { new MTest("-vf", new boolean[] { false, false }), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-str=%s{(john,zzzz]}", sh, 's', 1, "-str=",
- new RngCheck[] { new RngCheck("john", OPEN, "zzzz", CLOSED), },
- "", null);
-
- tests = new MTest[] { new MTest("-str=john", new MErr('r', "john")),
- new MTest("-str=joho ", "joho "),
- new MTest("-str=joho ", "joho "),
- new MTest("-str=zzzz", "zzzz"),
- new MTest("-str= joho", new MErr('r', " joho")),
- new MTest("-str=jnhn ", new MErr('r', "jnhn ")),
- new MTest("-str=zzzzz", new MErr('r', "zzzzz")),
- new MTest("-str=\"joho\"", new MErr('r', "\"joho\"")),
- new MTest("-str=\"joho", new MErr('r', "\"joho")),
- new MTest("-str=joho j", "joho j"), // new MErr('m', "joho j")),
- };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-str2=%s", sh, 's', 1, "-str2=", null, "", null);
- tests = new MTest[] { new MTest("-str2= jnhn", " jnhn"),
- new MTest("-str2=zzzzz", "zzzzz"), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-str3 %sX3", s3, 's', 3, "-str3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-str3 foo bar johnny", new String[] { "foo", "bar",
- "johnny" }),
- new MTest("-str3 zzzzz \"bad foo", new String[] { "zzzzz",
- "\"bad", "foo" }), // new MErr('m', "\"bad")),
- };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-strv3 %sX3", vec, 's', 3, "-strv3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-strv3 foo bar \"hihi\"", new String[] { "foo",
- "bar", "\"hihi\"" }, 0),
- new MTest("-strv3 a 123 gg", new String[] { "a", "123", "gg" },
- 1), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
- test.checkAdd("-strv=%s", vec, 's', 1, "-strv=", null, "", null);
- tests = new MTest[] { new MTest("-strv=d", "d", 0),
- new MTest("-strv='g'", "'g'", 1),
- new MTest("-strv=\\111", "\\111", 2), };
- vec.clear();
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=",
- new RngCheck[] { new RngCheck(-0.001, OPEN, 1000.0, CLOSED), },
- "", null);
-
- tests = new MTest[] {
- new MTest("-float=-0.000999", new Double(-0.000999)),
- new MTest("-float=1e-3", new Double(0.001)),
- new MTest("-float=12.33e1", new Double(123.3)),
- new MTest("-float=1e3", new Double(1e3)),
- new MTest("-float=1000.000", new Double(1000.0)),
- new MTest("-float=-0.001", new MErr('r', "-0.001")),
- new MTest("-float=-1e-3", new MErr('r', "-1e-3")),
- new MTest("-float=1000.001", new MErr('r', "1000.001")),
- new MTest("-float=.", new MErr('m', ".")),
- new MTest("-float= 124.5 ", new Double(124.5)),
- new MTest("-float=124.5x", new MErr('m', "124.5x")),
- new MTest("-float= foo ", new MErr('m', " foo ")),
- new MTest("-float=1e1", new Double(10)),
- new MTest("-float=1e ", new MErr('m', "1e ")), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-float2=%f", dh, 'f', 1, "-float2=", null, "", null);
- tests = new MTest[] { new MTest("-float2=-0.001", new Double(-0.001)),
- new MTest("-float2=-1e-3", new Double(-1e-3)),
- new MTest("-float2=1000.001", new Double(1000.001)), };
- test.checkMatches(tests, ONE_WORD);
-
- test.checkAdd("-f3 %fX3", d3, 'f', 3, "-f3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-f3 -0.001 1.23e5 -9.88e-4", new double[] { -0.001,
- 1.23e5, -9.88e-4 }),
- new MTest("-f3 7.88 foo 9.0", new MErr('m', "foo")),
- new MTest("-f3 7.88 . 9.0", new MErr('m', ".")),
- new MTest("-f3 7.88 3.0 9.0x", new MErr('m', "9.0x")), };
- test.checkMatches(tests, MULTI_WORD);
-
- test.checkAdd("-fv3 %fX3", vec, 'f', 3, "-fv3 ", null, "", null);
- tests = new MTest[] {
- new MTest("-fv3 1.0 3.444 6.7",
- new double[] { 1.0, 3.444, 6.7 }, 0),
- new MTest("-fv3 13e-5 145.678 0.0001e45", new double[] { 13e-5,
- 145.678, 0.0001e45 }, 1),
- new MTest("-fv3 11.11 3.1245 -1e-4", new double[] { 11.11,
- 3.1245, -1e-4 }, 2),
- new MTest("-fv3 1.0 2 3", new double[] { 1.0, 2.0, 3.0 }, 3), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
- test.checkAdd("-fv %f", vec, 'f', 1, "-fv ", null, "", null);
- tests = new MTest[] {
- new MTest("-fv -15.1234", new Double(-15.1234), 0),
- new MTest("-fv -1.234e-7", new Double(-1.234e-7), 1),
- new MTest("-fv 0.001111", new Double(0.001111), 2), };
- vec.clear();
- test.checkMatches(tests, MULTI_WORD);
-
- IntHolder intHolder = new IntHolder();
- StringHolder strHolder = new StringHolder();
-
- ArgParser parser = new ArgParser("test");
- parser.addOption("-foo %d #an int", intHolder);
- parser.addOption("-bar %s #a string", strHolder);
- args = new String[] { "zzz", "-cat", "-foo", "123", "yyy", "-bar",
- "xxxx", "xxx" };
-
- String[] unmatchedCheck = new String[] { "zzz", "-cat", "yyy", "xxx" };
-
- String[] unmatched = parser.matchAllArgs(args, 0, 0);
- test.checkStringArray("Unmatched args:", unmatched, unmatchedCheck);
-
- vec.clear();
- for (int i = 0; i < args.length;) {
- try {
- i = parser.matchArg(args, i);
- if (parser.getUnmatchedArgument() != null) {
- vec.add(parser.getUnmatchedArgument());
- }
- } catch (Exception e) {
- }
- }
- unmatched = (String[]) vec.toArray(new String[0]);
- test.checkStringArray("My unmatched args:", unmatched, unmatchedCheck);
-
- System.out.println("\nPassed\n");
-
- }
+public class ArgParserTest
+{
+ ArgParser parser;
+
+ static final boolean CLOSED = true;
+ static final boolean OPEN = false;
+
+ static final boolean ONE_WORD = true;
+ static final boolean MULTI_WORD = false;
+
+ private static void verify (boolean ok, String msg)
+ { if (!ok)
+ { Throwable e = new Throwable();
+ System.out.println ("Verification failed:" + msg);
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ private static String[] argsFromString (String s)
+ {
+ Vector<String> vec = new Vector<String>(100);
+ try
+ { ArgParser.stringToArgs (vec, s, /*allowQuotedStings=*/false);
+ }
+ catch (StringScanException e)
+ { e.printStackTrace();
+ System.exit (1);
+ }
+ String[] result = new String[vec.size()];
+ for (int i=0; i<vec.size(); i++)
+ { result[i] = (String)vec.get(i);
+ }
+ return result;
+ }
+
+ static class RngCheck
+ {
+ ArgParser.RangePnt low = null;
+ ArgParser.RangePnt high = null;
+ int type;
+
+ RngCheck (String s)
+ { low = new ArgParser.RangePnt (s, CLOSED);
+ type = 's';
+ }
+
+ RngCheck (double d)
+ { low = new ArgParser.RangePnt (d, CLOSED);
+ type = 'd';
+ }
+
+ RngCheck (long l)
+ { low = new ArgParser.RangePnt (l, CLOSED);
+ type = 'l';
+ }
+
+ RngCheck (boolean b)
+ { low = new ArgParser.RangePnt (b, CLOSED);
+ type = 'b';
+ }
+
+ RngCheck (String s1, boolean c1, String s2, boolean c2)
+ { low = new ArgParser.RangePnt (s1, c1);
+ high = new ArgParser.RangePnt (s2, c2);
+ type = 's';
+ }
+
+ RngCheck (double d1, boolean c1, double d2, boolean c2)
+ { low = new ArgParser.RangePnt (d1, c1);
+ high = new ArgParser.RangePnt (d2, c2);
+ type = 'd';
+ }
+
+ RngCheck (long l1, boolean c1, long l2, boolean c2)
+ { low = new ArgParser.RangePnt (l1, c1);
+ high = new ArgParser.RangePnt (l2, c2);
+ type = 'l';
+ }
+
+ void check (ArgParser.RangeAtom ra)
+ {
+ verify ((ra.low==null) == (low==null),
+ "(ra.low==null)=" + (ra.low==null) +
+ "(low==null)=" + (low==null));
+ verify ((ra.high==null) == (high==null),
+ "(ra.high==null)=" + (ra.high==null) +
+ "(high==null)=" + (high==null));
+
+ if (ra.low != null)
+ { switch (type)
+ { case 'l':
+ { verify (ra.low.lval==low.lval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 'd':
+ { verify (ra.low.dval==low.dval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 's':
+ { verify (ra.low.sval.equals (low.sval),
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ case 'b':
+ { verify (ra.low.bval==low.bval,
+ "ra.low=" + ra.low + " low=" + low);
+ break;
+ }
+ }
+ verify (ra.low.closed==low.closed,
+ "ra.low=" + ra.low + " low=" + low);
+ }
+ if (ra.high != null)
+ { switch (type)
+ { case 'l':
+ { verify (ra.high.lval==high.lval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 'd':
+ { verify (ra.high.dval==high.dval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 's':
+ { verify (ra.high.sval.equals (high.sval),
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ case 'b':
+ { verify (ra.high.bval==high.bval,
+ "ra.high=" + ra.high + " high=" + high);
+ break;
+ }
+ }
+ verify (ra.high.closed==high.closed,
+ "ra.high=" + ra.high + " high=" + high);
+ }
+ }
+ }
+
+ ArgParserTest ()
+ { parser = new ArgParser("fubar");
+ }
+
+ static void checkException (Exception e, String errmsg)
+ { if (errmsg != null)
+ { if (!e.getMessage().equals(errmsg))
+ { System.out.println (
+"Expecting exception '" + errmsg + "' but got '" +
+ e.getMessage() + "'");
+ e.printStackTrace();
+ (new Throwable()).printStackTrace();
+ System.exit(1);
+ }
+ }
+ else
+ { System.out.println (
+"Unexpected exception '" + e.getMessage() + "'");
+ e.printStackTrace();
+ (new Throwable()).printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ void checkPrintHelp (String msg)
+ {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
+ PrintStream ps = new PrintStream(buf);
+ ps.println (parser.getHelpMessage());
+ System.out.print (buf.toString());
+ }
+
+// void checkGetSynopsis (String msg)
+// {
+// ByteArrayOutputStream buf = new ByteArrayOutputStream(0x10000);
+// PrintStream ps = new PrintStream(buf);
+// parser.printSynopsis (ps, 80);
+// System.out.print (buf.toString());
+// }
+
+ void checkAdd (String s, Object resHolder, String errmsg)
+ {
+ checkAdd (s, resHolder, 0, 0, null, null, null, errmsg);
+ }
+
+ void add (String s, Object resHolder)
+ { try
+ { parser.addOption (s, resHolder);
+ }
+ catch (Exception e)
+ { e.printStackTrace();
+ System.exit (1);
+ }
+ }
+
+ void checkStringArray (String msg, String[] strs, String[] check)
+ {
+ boolean dontMatch = false;
+ if (strs.length != check.length)
+ { dontMatch = true;
+ }
+ else
+ { for (int i=0; i<strs.length; i++)
+ { if (!strs[i].equals (check[i]))
+ { dontMatch = true;
+ break;
+ }
+ }
+ }
+ if (dontMatch)
+ { System.out.println (msg);
+ System.out.print ("Expected: ");
+ for (int i=0; i<check.length; i++)
+ { System.out.print ("'" + check[i] + "'");
+ if (i<check.length-1)
+ { System.out.print (" ");
+ }
+ }
+ System.out.println ("");
+ System.out.print ("Got: ");
+ for (int i=0; i<strs.length; i++)
+ { System.out.print ("'" + strs[i] + "'");
+ if (i<strs.length-1)
+ { System.out.print (" ");
+ }
+ }
+ System.out.println ("");
+ System.exit(1);
+ }
+ }
+
+ void checkAdd (String s, Object resHolder, int code, int numValues,
+ Object names, RngCheck[] rngCheck,
+ String helpMsg, String errmsg)
+ {
+ boolean exceptionThrown = false;
+ String[] namelist = null;
+ try
+ { parser.addOption (s, resHolder);
+ }
+ catch (Exception e)
+ { exceptionThrown = true;
+ checkException (e, errmsg);
+ }
+ if (names instanceof String)
+ { namelist = new String[] { (String)names };
+ }
+ else
+ { namelist = (String[])names;
+ }
+ if (!exceptionThrown)
+ { verify (errmsg == null,
+ "Expecting exception " + errmsg);
+ ArgParser.Record rec = parser.lastMatchRecord();
+ verify (rec.convertCode==code,
+ "code=" + rec.convertCode + ", expecting " + code);
+ ArgParser.NameDesc nd;
+ int i=0;
+ for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next)
+ { i++;
+ }
+ verify (i==namelist.length,
+ "numNames=" + i + ", expecting " +namelist.length);
+ i=0;
+ for (nd=rec.firstNameDesc(); nd!=null; nd=nd.next)
+ { String ss;
+ if (!nd.oneWord)
+ { ss = new String(nd.name) + ' ';
+ }
+ else
+ { ss = nd.name;
+ }
+ verify (ss.equals(namelist[i]),
+ "have name '"+ss+"', expecting '"+namelist[i]+"'");
+ i++;
+ }
+ ArgParser.RangeAtom ra;
+ i=0;
+ for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next)
+ { i++;
+ }
+ int expectedRangeNum = 0;
+ if (rngCheck!=null)
+ { expectedRangeNum = rngCheck.length;
+ }
+ verify (i==expectedRangeNum,
+ "numRangeAtoms="+i+", expecting "+expectedRangeNum);
+ i=0;
+ for (ra=rec.firstRangeAtom(); ra!=null; ra=ra.next)
+ { rngCheck[i++].check(ra);
+ }
+ verify (rec.helpMsg.equals(helpMsg),
+ "helpMsg="+rec.helpMsg+", expecting "+helpMsg);
+ verify (rec.numValues==numValues,
+ "numValues="+rec.numValues+", expecting "+numValues);
+ }
+ }
+
+ double getDoubleValue (Object obj, int k)
+ {
+ if (obj instanceof DoubleHolder)
+ { return ((DoubleHolder)obj).value;
+ }
+ else if (obj instanceof FloatHolder)
+ { return ((FloatHolder)obj).value;
+ }
+ else if (obj instanceof double[])
+ { return ((double[])obj)[k];
+ }
+ else if (obj instanceof float[])
+ { return ((float[])obj)[k];
+ }
+ else
+ { verify (false, "object doesn't contain double values");
+ return 0;
+ }
+ }
+
+ long getLongValue (Object obj, int k)
+ {
+ if (obj instanceof LongHolder)
+ { return ((LongHolder)obj).value;
+ }
+ else if (obj instanceof IntHolder)
+ { return ((IntHolder)obj).value;
+ }
+ else if (obj instanceof long[])
+ { return ((long[])obj)[k];
+ }
+ else if (obj instanceof int[])
+ { return ((int[])obj)[k];
+ }
+ else
+ { verify (false, "object doesn't contain long values");
+ return 0;
+ }
+ }
+
+ String getStringValue (Object obj, int k)
+ {
+ if (obj instanceof StringHolder)
+ { return ((StringHolder)obj).value;
+ }
+ else if (obj instanceof String[])
+ { return ((String[])obj)[k];
+ }
+ else
+ { verify (false, "object doesn't contain String values");
+ return null;
+ }
+ }
+
+ boolean getBooleanValue (Object obj, int k)
+ {
+ if (obj instanceof BooleanHolder)
+ { return ((BooleanHolder)obj).value;
+ }
+ else if (obj instanceof boolean[])
+ { return ((boolean[])obj)[k];
+ }
+ else
+ { verify (false, "object doesn't contain boolean values");
+ return false;
+ }
+ }
+
+ char getCharValue (Object obj, int k)
+ {
+ if (obj instanceof CharHolder)
+ { return ((CharHolder)obj).value;
+ }
+ else if (obj instanceof char[])
+ { return ((char[])obj)[k];
+ }
+ else
+ { verify (false, "object doesn't contain char values");
+ return 0;
+ }
+ }
+
+ static class MErr
+ {
+ int code;
+ String valStr;
+
+ MErr (int code, String valStr)
+ { this.code = code;
+ this.valStr = valStr;
+ }
+ }
+
+ static class MTest
+ {
+ String args;
+ Object result;
+ int resultIdx;
+
+ MTest (String args, Object result)
+ { this (args, result, -1);
+ }
+
+ MTest (String args, Object result, int resultIdx)
+ { this.args = args;
+ this.result = result;
+ this.resultIdx = resultIdx;
+ }
+ };
+
+ void checkMatch (String args[], int idx, String errMsg)
+ { getMatchResult (args, idx, -1, errMsg, -1);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ long check, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ long result = getLongValue(rholder,0);
+ verify (result==check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ double check, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ double result = getDoubleValue(rholder,0);
+ verify (result==check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ String check, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ String result = getStringValue(rholder,0);
+ verify (result.equals(check), "result " + result + " vs. " + check);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ boolean check, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ boolean result = getBooleanValue(rholder,0);
+ verify (result==check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ char check, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ char result = getCharValue(rholder,0);
+ verify (result==check, "result " + result + " vs. " + check);
+ }
+
+ void checkMatch (String args[], int idx, int cnt,
+ Object checkArray, int resultIdx)
+ { Object rholder = getMatchResult (args, idx, cnt, null, resultIdx);
+ if (!checkArray.getClass().isArray())
+ { verify (false, "check is not an array");
+ }
+ for (int i=0; i<Array.getLength(checkArray); i++)
+ { if (checkArray instanceof long[])
+ { long result = getLongValue(rholder,i);
+ long check = ((long[])checkArray)[i];
+ verify (result==check,
+ "result ["+i+"] " + result + " vs. " + check);
+ }
+ else if (checkArray instanceof double[])
+ { double result = getDoubleValue(rholder,i);
+ double check = ((double[])checkArray)[i];
+ verify (result==check,
+ "result ["+i+"] " + result + " vs. " + check);
+ }
+ else if (checkArray instanceof String[])
+ { String result = getStringValue(rholder,i);
+ String check = ((String[])checkArray)[i];
+ verify (result.equals(check),
+ "result ["+i+"] " + result + " vs. " + check);
+ }
+ else if (checkArray instanceof boolean[])
+ { boolean result = getBooleanValue(rholder,i);
+ boolean check = ((boolean[])checkArray)[i];
+ verify (result==check,
+ "result ["+i+"] " + result + " vs. " + check);
+ }
+ else if (checkArray instanceof char[])
+ { char result = getCharValue(rholder,i);
+ char check = ((char[])checkArray)[i];
+ verify (result==check,
+ "result ["+i+"] " + result + " vs. " + check);
+ }
+ else
+ { verify (false, "unknown type for checkArray");
+ }
+ }
+ }
+
+ void checkMatch (MTest test, boolean oneWord)
+ { String[] argv;
+ if (oneWord)
+ { argv = new String[1];
+ argv[0] = test.args;
+ }
+ else
+ { argv = argsFromString(test.args);
+ }
+ if (test.result instanceof Long)
+ { checkMatch (argv, 0, argv.length,
+ ((Long)test.result).longValue(),
+ test.resultIdx);
+ }
+ else if (test.result instanceof Double)
+ { checkMatch (argv, 0, argv.length,
+ ((Double)test.result).doubleValue(),
+ test.resultIdx);
+ }
+ else if (test.result instanceof String)
+ { checkMatch (argv, 0, argv.length,
+ (String)test.result,
+ test.resultIdx);
+ }
+ else if (test.result instanceof Boolean)
+ { checkMatch (argv, 0, argv.length,
+ ((Boolean)test.result).booleanValue(),
+ test.resultIdx);
+ }
+ else if (test.result instanceof Character)
+ { checkMatch (argv, 0, argv.length,
+ ((Character)test.result).charValue(),
+ test.resultIdx);
+ }
+ else if (test.result.getClass().isArray())
+ { checkMatch (argv, 0, argv.length, test.result,
+ test.resultIdx);
+ }
+ else if (test.result instanceof MErr)
+ { MErr err = (MErr)test.result;
+ String argname = parser.getOptionName (argv[0]);
+ String msg = "";
+
+ switch (err.code)
+ { case 'c':
+ { msg = "requires a contiguous value";
+ break;
+ }
+ case 'm':
+ { msg = "malformed " + parser.getOptionTypeName(argv[0]) +
+ " '" + err.valStr + "'";
+ break;
+ }
+ case 'r':
+ { msg = "value '" + err.valStr + "' not in range " +
+ parser.getOptionRangeDesc(argv[0]);
+ break;
+ }
+ case 'v':
+ { msg = "requires " + err.valStr + " values";
+ break;
+ }
+ }
+ checkMatch (argv, 0, argname + ": " + msg);
+ }
+ else
+ { verify (false, "Unknown result type");
+ }
+ }
+
+ void checkMatches (MTest[] tests, boolean oneWord)
+ { for (int i=0; i<tests.length; i++)
+ { checkMatch (tests[i], oneWord);
+ }
+ }
+
+ Object getMatchResult (String args[], int idx, int cnt,
+ String errMsg, int resultIdx)
+ {
+ boolean exceptionThrown = false;
+ int k = 0;
+ try
+ { k = parser.matchArg (args, idx);
+ }
+ catch (Exception e)
+ { exceptionThrown = true;
+ checkException (e, errMsg);
+ }
+ if (!exceptionThrown)
+ { verify (k==idx+cnt,
+ "Expecting result index " + (idx+cnt) + ", got " + k);
+ Object result = parser.getResultHolder(args[0]);
+ if (resultIdx >= 0)
+ { verify (result instanceof Vector,
+ "Expecting result to be stored in a vector");
+ Vector<?> vec = (Vector<?>)result;
+ verify (vec.size()==resultIdx+1,
+ "Expecting result vector size " + (resultIdx+1));
+ return vec.get(resultIdx);
+ }
+ else
+ { return result;
+ }
+ }
+ else
+ { return null;
+ }
+ }
+
+ /**
+ * Runs a set of tests to verify correct operation of the
+ * ArgParser class. If all the tests run correctly, the
+ * program prints the message <code>Passed</code> and terminates.
+ * Otherwise, diagnostic information is printed at the first
+ * point of failure.
+ */
+ public static void main (String[] args)
+ {
+ ArgParserTest test = new ArgParserTest();
+
+ BooleanHolder bh = new BooleanHolder();
+ boolean[] b3 = new boolean[3];
+ CharHolder ch = new CharHolder();
+ char[] c3 = new char[3];
+ IntHolder ih = new IntHolder();
+ int[] i3 = new int[3];
+ LongHolder lh = new LongHolder();
+ long[] l3 = new long[3];
+ FloatHolder fh = new FloatHolder();
+ float[] f3 = new float[3];
+ DoubleHolder dh = new DoubleHolder();
+ double[] d3 = new double[3];
+ StringHolder sh = new StringHolder();
+ String[] s3 = new String[3];
+
+ test.checkAdd ("-foo %i{[0,10)}X3 #sets the value of foo",
+// 0123456789012345
+ i3, 'i', 3, new String[] { "-foo " },
+ new RngCheck[] {
+ new RngCheck(0, CLOSED, 10, OPEN) },
+ "sets the value of foo", null);
+
+ test.checkAdd ("-arg1,,", null, "Null option name given");
+ test.checkAdd ("-arg1,,goo %f ", null, "Null option name given");
+ test.checkAdd (" ", null, "Null option name given");
+ test.checkAdd ("", null, "Null option name given");
+ test.checkAdd (" %v", null, "Null option name given");
+ test.checkAdd ("-foo ", null, "No conversion character given");
+ test.checkAdd ("-foo %", null, "No conversion character given");
+ test.checkAdd ("foo, aaa bbb ",null,"Names not separated by ','");
+ test.checkAdd (" foo aaa %d", null, "Names not separated by ','");
+ test.checkAdd ("-arg1,-b,", null, "Null option name given");
+ test.checkAdd ("-arg1,-b", null, "No conversion character given");
+ test.checkAdd ("-arg1 ", null, "No conversion character given");
+ test.checkAdd ("-arg1, %v", null, "Null option name given");
+ test.checkAdd ("-arg1,%v", null, "Null option name given");
+ test.checkAdd ("-foo %V", null,
+ "Conversion code 'V' not one of 'iodxcbfsvh'");
+ test.checkAdd ("-h %hX5",null,"Multipliers not supported for %h");
+ test.checkAdd ("-h %h{}",null,"Ranges not supported for %h");
+ test.checkAdd ("-help, -h %h #here is how we help you",
+ null, 'h', 1, new String[] {"-help ", "-h " },
+ null, "here is how we help you", null);
+
+ test.checkAdd (
+ "-arg1 ,-arg2=%d{0,3,(7,16]}X1 #x3 test",
+ l3, 'd', 1, new String[] { "-arg1 ", "-arg2=" },
+ new RngCheck[]
+ { new RngCheck(0),
+ new RngCheck(3),
+ new RngCheck(7, OPEN, 16, CLOSED),
+ },
+ "x3 test", null);
+
+ test.checkAdd (
+ "bbb,ccc%x{[1,2]} #X3 x3 test",
+ l3, 'x', 1, new String[] { "bbb", "ccc" },
+ new RngCheck[]
+ { new RngCheck(1, CLOSED, 2, CLOSED),
+ },
+ "X3 x3 test", null);
+
+ test.checkAdd (
+ " bbb ,ccc, ddd ,e , f=%bX1 #x3 test",
+ b3, 'b', 1, new String[] { "bbb ", "ccc", "ddd ", "e ", "f=" },
+ null,
+ "x3 test", null);
+
+ test.checkAdd (
+ " bbb ,ccc, ddd ,e , f= %bX3 #x3 test",
+ b3, 'b', 3, new String[] { "bbb ", "ccc ", "ddd ", "e ","f= " },
+ null,
+ "x3 test", null);
+
+ test.checkAdd (
+ "-b,--bar %s{[\"john\",\"jerry\"),fred,\"harry\"} #sets bar",
+ sh, 's', 1, new String[] { "-b ", "--bar " },
+ new RngCheck[] {
+ new RngCheck("jerry",OPEN,"john",CLOSED),
+ new RngCheck("fred"),
+ new RngCheck("harry") },
+ "sets bar", null);
+
+ test.checkAdd (
+ "-c ,coven%f{0.0,9.0,(6,5],[-9.1,10.2]} ",
+ dh, 'f', 1, new String[] { "-c ", "coven" },
+ new RngCheck[] {
+ new RngCheck(0.0),
+ new RngCheck(9.0),
+ new RngCheck(5.0,CLOSED,6.0,OPEN),
+ new RngCheck(-9.1,CLOSED,10.2,CLOSED) },
+ "", null);
+
+ test.checkAdd (
+ "-b %b #a boolean value ",
+ bh, 'b', 1, new String[] { "-b "},
+ new RngCheck[] { },
+ "a boolean value ", null);
+
+ test.checkAdd ("-a %i", ih, 'i', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %o", lh, 'o', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %d", i3, 'd', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %x", l3, 'x', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %c", ch, 'c', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %c", c3, 'c', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %v", bh, 'v', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %b", b3, 'b', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %f", fh, 'f', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %f", f3, 'f', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %f", dh, 'f', 1, "-a ", null, "", null);
+ test.checkAdd ("-a %f", d3, 'f', 1, "-a ", null, "", null);
+
+ test.checkAdd ("-a %i", fh, 'i', 1, "-a ", null, "",
+ "Invalid result holder for %i");
+ test.checkAdd ("-a %c", i3, 'c', 1, "-a ", null, "",
+ "Invalid result holder for %c");
+ test.checkAdd ("-a %v", d3, 'v', 1, "-a ", null, "",
+ "Invalid result holder for %v");
+ test.checkAdd ("-a %f", sh, 'f', 1, "-a ", null, "",
+ "Invalid result holder for %f");
+ test.checkAdd ("-a %s", l3, 's', 1, "-a ", null, "",
+ "Invalid result holder for %s");
+
+ test.checkAdd ("-foo %i{} ", ih, 'i', 1, "-foo ", null, "", null);
+ test.checkAdd ("-foo%i{}", ih, 'i', 1, "-foo", null, "", null);
+ test.checkAdd ("-foo%i{ }", ih, 'i', 1, "-foo", null, "", null);
+ test.checkAdd ("-foo%i{ }}", ih,
+ "Illegal character(s), expecting '#'");
+ test.checkAdd ("-foo%i{ ", ih,"Unterminated range specification");
+ test.checkAdd ("-foo%i{", ih, "Unterminated range specification");
+ test.checkAdd ("-foo%i{0,9", ih, "Unterminated range specification");
+ test.checkAdd ("-foo%i{1,2,3)", ih,
+ "Unterminated range specification");
+
+ test.checkAdd ("-b %f{0.9}", fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9) },
+ "", null);
+ test.checkAdd ("-b %f{ 0.9 ,7, -0.5,-4 ,6 }", fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9),
+ new RngCheck(7.0),
+ new RngCheck(-0.5),
+ new RngCheck(-4.0),
+ new RngCheck(6.0) },
+ "", null);
+ test.checkAdd ("-b %f{ [0.9,7), (-0.5,-4),[9,6] , (10,13.4] }",
+ fh, 'f', 1, "-b ",
+ new RngCheck[] { new RngCheck(0.9,CLOSED,7.0,OPEN),
+ new RngCheck(-4.0,OPEN,-.5,OPEN),
+ new RngCheck(6.0,CLOSED,9.0,CLOSED),
+ new RngCheck(10.0,OPEN,13.4,CLOSED),
+ },
+ "", null);
+ test.checkAdd ("-b %f{(8 9]}", fh,
+ "Missing ',' in subrange specification");
+ test.checkAdd ("-b %f{(8,9,]}", fh,
+ "Unterminated subrange");
+ test.checkAdd ("-b %f{(8,9 ,]}", fh,
+ "Unterminated subrange");
+ test.checkAdd ("-b %f{(8,9 8]}", fh,
+ "Unterminated subrange");
+ test.checkAdd ("-b %f{8 9}", fh,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd ("-b %f{8 *}", fh,
+ "Range spec: ',' or '}' expected");
+
+ test.checkAdd ("-b %f{8y}", fh,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd ("-b %f{.}", fh,
+ "Malformed float '.}' in range spec");
+ test.checkAdd ("-b %f{1.0e}", fh,
+ "Malformed float '1.0e}' in range spec");
+ test.checkAdd ("-b %f{[*]}", fh,
+ "Malformed float '*' in range spec");
+ test.checkAdd ("-b %f{1.2e5t}", fh,
+ "Range spec: ',' or '}' expected");
+
+
+ test.checkAdd ("-b %i{8}", ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8) },
+ "", null);
+ test.checkAdd ("-b %i{8, 9,10 }", ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8),
+ new RngCheck(9),
+ new RngCheck(10) },
+ "", null);
+ test.checkAdd ("-b %i{8, [-9,10),[-17,15],(2,-33),(8,9] }",
+ ih, 'i', 1, "-b ",
+ new RngCheck[] { new RngCheck(8),
+ new RngCheck(-9,CLOSED,10,OPEN),
+ new RngCheck(-17,CLOSED,15,CLOSED),
+ new RngCheck(-33,OPEN,2,OPEN),
+ new RngCheck(8,OPEN,9,CLOSED),
+ },
+ "", null);
+ test.checkAdd ("-b %i{8.7}", ih,
+ "Range spec: ',' or '}' expected");
+ test.checkAdd ("-b %i{6,[*]}", ih,
+ "Malformed integer '*' in range spec");
+ test.checkAdd ("-b %i{g76}", ih,
+ "Malformed integer 'g' in range spec");
+
+ test.checkAdd ("-b %s{foobar}", sh, 's', 1, "-b ",
+ new RngCheck[] { new RngCheck("foobar") },
+ "", null);
+ test.checkAdd ("-b %s{foobar, 0x233,\" \"}", sh, 's', 1, "-b ",
+ new RngCheck[] { new RngCheck("foobar"),
+ new RngCheck("0x233"),
+ new RngCheck(" ") },
+ "", null);
+ test.checkAdd ("-b %s{foobar,(bb,aa], [\"01\",02]}",
+ sh, 's', 1, "-b ",
+ new RngCheck[]
+ { new RngCheck("foobar"),
+ new RngCheck("aa",CLOSED,"bb",OPEN),
+ new RngCheck("01",CLOSED,"02",CLOSED),
+ },
+ "", null);
+
+ test.checkAdd ("-b %c{'a'}", ch, 'c', 1, "-b ",
+ new RngCheck[] { new RngCheck('a') },
+ "", null);
+ test.checkAdd ("-b %c{'\\n', '\\002', 'B'}", ch, 'c', 1, "-b ",
+ new RngCheck[] { new RngCheck('\n'),
+ new RngCheck('\002'),
+ new RngCheck('B') },
+ "", null);
+ test.checkAdd ("-b %c{'q',('g','a'], ['\t','\\003']}",
+ ch, 'c', 1, "-b ",
+ new RngCheck[]
+ { new RngCheck('q'),
+ new RngCheck('a',CLOSED,'g',OPEN),
+ new RngCheck('\003',CLOSED,'\t',CLOSED),
+ },
+ "", null);
+
+ test.checkAdd ("-b %b{true}X2", b3, 'b', 2, "-b ",
+ new RngCheck[] { new RngCheck(true) },
+ "", null);
+ test.checkAdd ("-b %b{ true , false, true }", bh, 'b', 1, "-b ",
+ new RngCheck[] { new RngCheck(true),
+ new RngCheck(false),
+ new RngCheck(true) },
+ "", null);
+ test.checkAdd ("-b %v{true,[true,false)}", bh,
+ "Sub ranges not supported for %b or %v");
+ test.checkAdd ("-b %v{true,[]}", bh,
+ "Sub ranges not supported for %b or %v");
+ test.checkAdd ("-b %b{tru}", bh,
+ "Malformed boolean 'tru}' in range spec");
+
+ test.checkAdd ("-b %iX2", i3, 'i', 2, "-b ", null, "", null);
+ test.checkAdd ("-b %vX3", b3, 'v', 3, "-b ", null, "", null);
+ test.checkAdd ("-b %v{ }X3", b3, 'v', 3, "-b ", null, "", null);
+
+ test.checkAdd ("-b=%iX2", i3, 'i', 2, "-b", null, "",
+"Multiplier value incompatible with one word option -b=");
+ test.checkAdd ("-b %iX0", i3, 'i', 0, "-b ", null, "",
+ "Value multiplier number must be > 0");
+ test.checkAdd ("-b %iX-6", i3, 'i', 0, "-b ", null, "",
+ "Value multiplier number must be > 0");
+ test.checkAdd ("-b %iXy", i3, 'i', 0, "-b ", null, "",
+ "Malformed value multiplier");
+ test.checkAdd ("-b %iX4", i3, 'i', 4, "-b ", null, "",
+ "Result holder array must have a length >= 4");
+ test.checkAdd ("-b %iX4", ih, 'i', 4, "-b ", null, "",
+"Multiplier requires result holder to be an array of length >= 4");
+
+ test.checkAdd ("-b %i #X4", ih, 'i', 1, "-b ", null, "X4", null);
+ test.checkAdd ("-b %i #[}X4",ih, 'i', 1, "-b ", null, "[}X4", null);
+
+// test.checkPrintHelp("");
+// test.checkPrintUsage("");
+
+ test = new ArgParserTest();
+
+ test.checkAdd (
+ "-intarg %i{1,2,(9,18],[22,27],[33,38),(45,48)} #test int arg",
+ ih, 'i', 1, "-intarg ",
+ new RngCheck[]
+ { new RngCheck (1),
+ new RngCheck (2),
+ new RngCheck (9,OPEN,18,CLOSED),
+ new RngCheck (22,CLOSED,27,CLOSED),
+ new RngCheck (33,CLOSED,38,OPEN),
+ new RngCheck (45,OPEN,48,OPEN),
+ },
+ "test int arg", null);
+
+ MTest[] tests;
+
+ tests = new MTest[]
+ {
+ new MTest("-intarg 1", new Long(1) ),
+ new MTest("-intarg 3", new MErr ('r', "3") ),
+ new MTest("-intarg 9", new MErr ('r', "9") ),
+ new MTest("-intarg 11", new Long(11) ),
+ new MTest("-intarg 18", new Long(18)),
+ new MTest("-intarg 22", new Long(22)),
+ new MTest("-intarg 25", new Long(25)),
+ new MTest("-intarg 27", new Long(27)),
+ new MTest("-intarg 33", new Long(33)),
+ new MTest("-intarg 35", new Long(35)),
+ new MTest("-intarg 38", new MErr ('r', "38") ),
+ new MTest("-intarg 45", new MErr ('r', "45")),
+ new MTest("-intarg 46", new Long(46)),
+ new MTest("-intarg 48", new MErr ('r', "48")),
+ new MTest("-intarg 100", new MErr ('r', "100")),
+ new MTest("-intarg 0xbeef", new MErr ('r', "0xbeef")),
+ new MTest("-intarg 0x2f", new Long (0x2f)),
+ new MTest("-intarg 041", new Long(041) ),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-farg %f{1,2,(9,18],[22,27],[33,38),(45,48)} #test float arg",
+ dh, 'f', 1, "-farg ",
+ new RngCheck[]
+ {
+ new RngCheck (1.0),
+ new RngCheck (2.0),
+ new RngCheck (9.0,OPEN,18.0,CLOSED),
+ new RngCheck (22.0,CLOSED,27.0,CLOSED),
+ new RngCheck (33.0,CLOSED,38.0,OPEN),
+ new RngCheck (45.0,OPEN,48.0,OPEN),
+ },
+ "test float arg", null);
+
+ tests = new MTest[]
+ {
+ new MTest("-farg 1", new Double(1)),
+ new MTest("-farg 3", new MErr('r', "3")),
+ new MTest("-farg 9", new MErr('r', "9")),
+ new MTest("-farg 9.0001", new Double(9.0001)),
+ new MTest("-farg 11", new Double(11)),
+ new MTest("-farg 18", new Double(18)),
+ new MTest("-farg 22", new Double(22)),
+ new MTest("-farg 25", new Double(25)),
+ new MTest("-farg 27", new Double(27)),
+ new MTest("-farg 33", new Double(33)),
+ new MTest("-farg 35", new Double(35)),
+ new MTest("-farg 37.9999",new Double(37.9999)),
+ new MTest("-farg 38", new MErr('r', "38")),
+ new MTest("-farg 45", new MErr('r', "45")),
+ new MTest("-farg 45.0001", new Double(45.0001)),
+ new MTest("-farg 46",new Double(46)),
+ new MTest("-farg 47.9999",new Double(47.9999)),
+ new MTest("-farg 48", new MErr('r', "48")),
+ new MTest("-farg 100", new MErr('r', "100")),
+ new MTest("-farg 0", new MErr('r', "0")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-sarg %s{1,2,(AA,AZ],[BB,BX],[C3,C8),(d5,d8)} #test string arg",
+ s3, 's', 1, "-sarg ",
+ new RngCheck[]
+ { new RngCheck ("1"),
+ new RngCheck ("2"),
+ new RngCheck ("AA",OPEN,"AZ",CLOSED),
+ new RngCheck ("BB",CLOSED,"BX",CLOSED),
+ new RngCheck ("C3",CLOSED,"C8",OPEN),
+ new RngCheck ("d5",OPEN,"d8",OPEN),
+ },
+ "test string arg", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-sarg 1", "1"),
+ new MTest ("-sarg 3", new MErr('r',"3")),
+ new MTest ("-sarg AA", new MErr('r',"AA")),
+ new MTest ("-sarg AM", "AM"),
+ new MTest ("-sarg AZ", "AZ"),
+ new MTest ("-sarg BB", "BB"),
+ new MTest ("-sarg BL", "BL"),
+ new MTest ("-sarg BX", "BX"),
+ new MTest ("-sarg C3", "C3"),
+ new MTest ("-sarg C6", "C6"),
+ new MTest ("-sarg C8", new MErr('r',"C8")),
+ new MTest ("-sarg d5", new MErr('r',"d5")),
+ new MTest ("-sarg d6", "d6"),
+ new MTest ("-sarg d8", new MErr('r',"d8")),
+ new MTest ("-sarg zzz", new MErr('r',"zzz")),
+ new MTest ("-sarg 0", new MErr('r',"0")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test = new ArgParserTest();
+
+ test.checkAdd (
+ "-carg %c{1,2,(a,z],['A','Z'],['\\001',\\007),(4,8)}",
+ c3, 'c', 1, "-carg ",
+ new RngCheck[]
+ { new RngCheck ('1'),
+ new RngCheck ('2'),
+ new RngCheck ('a',OPEN,'z',CLOSED),
+ new RngCheck ('A',CLOSED,'Z',CLOSED),
+ new RngCheck ('\001',CLOSED,'\007',OPEN),
+ new RngCheck ('4',OPEN,'8',OPEN),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-carg 1", new Character('1')),
+ new MTest ("-carg 3", new MErr('r',"3")),
+ new MTest ("-carg a", new MErr('r',"a")),
+ new MTest ("-carg m", new Character('m')),
+ new MTest ("-carg z", new Character('z')),
+ new MTest ("-carg A", new Character('A')),
+ new MTest ("-carg 'L'", new Character('L')),
+ new MTest ("-carg 'Z'", new Character('Z')),
+ new MTest ("-carg \\001", new Character('\001')),
+ new MTest ("-carg \\005", new Character('\005')),
+ new MTest ("-carg '\\007'", new MErr('r',"'\\007'")),
+ new MTest ("-carg '4'", new MErr('r',"'4'")),
+ new MTest ("-carg 6", new Character('6')),
+ new MTest ("-carg 8", new MErr('r',"8")),
+ new MTest ("-carg '\\012'", new MErr('r',"'\\012'")),
+ new MTest ("-carg 0", new MErr('r',"0")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-foo=%i{[-50,100]}", ih, 'i', 1, "-foo=",
+ new RngCheck[]
+ { new RngCheck (-50,CLOSED,100,CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-foo=-51", new MErr('r',"-51")),
+ new MTest ("-foo=-0x32", new Long(-0x32)),
+ new MTest ("-foo=-0x33", new MErr('r',"-0x33")),
+ new MTest ("-foo=-0777", new MErr('r',"-0777")),
+ new MTest ("-foo=-07", new Long(-07)),
+ new MTest ("-foo=0", new Long(0)),
+ new MTest ("-foo=100", new Long(100)),
+ new MTest ("-foo=0x5e", new Long(0x5e)),
+ new MTest ("-foo=066", new Long(066)),
+ new MTest ("-foo=06677", new MErr('r',"06677")),
+ new MTest ("-foo=0xbeef", new MErr('r',"0xbeef")),
+ new MTest ("-foo=foo", new MErr('m',"foo")),
+ new MTest ("-foo=-51d", new MErr('m',"-51d")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-foo2=%i", ih, 'i', 1, "-foo2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-foo2=-51", new Long(-51)),
+ new MTest ("-foo2=-0x33", new Long(-0x33)),
+ new MTest ("-foo2=-0777", new Long(-0777)),
+ new MTest ("-foo2=06677", new Long(06677)),
+ new MTest ("-foo2=0xbeef", new Long(0xbeef)),
+ new MTest ("-foo2=foo", new MErr('m',"foo")),
+ new MTest ("-foo2=-51d", new MErr('m',"-51d")),
+ new MTest ("-foo2=-51", new Long(-51)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-foo3 %iX3", i3, 'i', 3, "-foo3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-foo3 -51 678 0x45",
+ new long[] { -51, 678, 0x45 }),
+ new MTest ("-foo3 55 16f 55", new MErr ('m', "16f")),
+ new MTest ("-foo3 55 16", new MErr ('v', "3")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ Vector<String> vec = new Vector<String>(100);
+
+ test.checkAdd ("-foov3 %iX3", vec,'i',3,"-foov3 ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-foov3 -1 2 4", new long[] {-1, 2, 4}, 0),
+ new MTest ("-foov3 10 3 9", new long[] {10, 3, 9}, 1),
+ new MTest ("-foov3 123 1 0", new long[] {123, 1, 0}, 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+ test.checkAdd ("-foov %i", vec,'i',1,"-foov ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-foov 11", new Long(11), 0),
+ new MTest ("-foov 12", new Long(12), 1),
+ new MTest ("-foov 13", new Long(13), 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-foo4 %i{[-50,100]}X2", i3, 'i', 2, "-foo4 ",
+ new RngCheck[]
+ { new RngCheck (-50,CLOSED,100,CLOSED),
+ },
+ "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-foo4 -49 78",
+ new long[] { -49, 78 }),
+ new MTest ("-foo4 -48 102", new MErr ('r', "102")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-oct=%o{[-062,0144]}", ih, 'o', 1, "-oct=",
+ new RngCheck[]
+ { new RngCheck (-50,CLOSED,100,CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-oct=-063", new MErr('r',"-063")),
+ new MTest ("-oct=-0x32", new MErr('m',"-0x32")),
+ new MTest ("-oct=-0777", new MErr('r',"-0777")),
+ new MTest ("-oct=-07", new Long(-07)),
+ new MTest ("-oct=0", new Long(0)),
+ new MTest ("-oct=100", new Long(64)),
+ new MTest ("-oct=0xae", new MErr('m',"0xae")),
+ new MTest ("-oct=66", new Long(066)),
+ new MTest ("-oct=06677", new MErr('r',"06677")),
+ new MTest ("-oct=0xbeef", new MErr('m',"0xbeef")),
+ new MTest ("-oct=foo", new MErr('m',"foo")),
+ new MTest ("-oct=-51d", new MErr('m',"-51d")),
+ new MTest ("-oct=78", new MErr('m',"78")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-oct2=%o", ih, 'o', 1, "-oct2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-oct2=-063", new Long(-063)),
+ new MTest ("-oct2=-0777", new Long(-0777)),
+ new MTest ("-oct2=06677", new Long(06677)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-dec=%d{[-0x32,0x64]}", ih, 'd', 1, "-dec=",
+ new RngCheck[]
+ { new RngCheck (-50,CLOSED,100,CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-dec=-063", new MErr('r',"-063")),
+ new MTest ("-dec=-0x32", new MErr('m',"-0x32")),
+ new MTest ("-dec=-0777", new MErr('r',"-0777")),
+ new MTest ("-dec=-07", new Long(-07)),
+ new MTest ("-dec=0", new Long(0)),
+ new MTest ("-dec=100", new Long(100)),
+ new MTest ("-dec=0xae", new MErr('m',"0xae")),
+ new MTest ("-dec=66", new Long(66)),
+ new MTest ("-dec=06677", new MErr('r',"06677")),
+ new MTest ("-dec=0xbeef", new MErr('m',"0xbeef")),
+ new MTest ("-dec=foo", new MErr('m',"foo")),
+ new MTest ("-dec=-51d", new MErr('m',"-51d")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-dec2=%d", ih, 'd', 1, "-dec2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-dec2=-063", new Long(-63)),
+ new MTest ("-dec2=-0777", new Long(-777)),
+ new MTest ("-dec2=06677", new Long(6677)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-hex=%x{[-0x32,0x64]}", ih, 'x', 1, "-hex=",
+ new RngCheck[]
+ { new RngCheck (-50,CLOSED,100,CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-hex=-06", new Long(-0x6)),
+ new MTest ("-hex=-0x3g2", new MErr('m',"-0x3g2")),
+ new MTest ("-hex=-0777", new MErr('r',"-0777")),
+ new MTest ("-hex=-017", new Long(-0x17)),
+ new MTest ("-hex=0", new Long(0)),
+ new MTest ("-hex=64", new Long(0x64)),
+ new MTest ("-hex=5e", new Long(0x5e)),
+ new MTest ("-hex=66", new MErr('r',"66")),
+ new MTest ("-hex=06677", new MErr('r',"06677")),
+ new MTest ("-hex=0xbeef", new MErr('m',"0xbeef")),
+ new MTest ("-hex=foo", new MErr('m',"foo")),
+ new MTest ("-hex=-51d", new MErr('r',"-51d")),
+ new MTest ("-hex=-51g", new MErr('m',"-51g")),
+ new MTest ("-hex=", new MErr('c',"")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-hex2=%x", ih, 'x', 1, "-hex2=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-hex2=-0777", new Long(-0x777)),
+ new MTest ("-hex2=66", new Long(0x66)),
+ new MTest ("-hex2=06677", new Long(0x6677)),
+ new MTest ("-hex2=-51d", new Long(-0x51d)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-char=%c{['b','m']}", ch, 'c', 1, "-char=",
+ new RngCheck[]
+ { new RngCheck ('b',CLOSED,'m',CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-char=a", new MErr('r',"a")),
+ new MTest ("-char=b", new Character('b')),
+ new MTest ("-char='b'", new Character('b')),
+ new MTest ("-char='\142'", new Character('b')),
+ new MTest ("-char='\141'", new MErr('r',"'\141'")),
+ new MTest ("-char=\142", new Character('b')),
+ new MTest ("-char=\141", new MErr('r',"\141")),
+ new MTest ("-char=m", new Character('m')),
+ new MTest ("-char=z", new MErr('r', "z")),
+ new MTest ("-char=bb", new MErr('m', "bb")),
+ new MTest ("-char='b", new MErr('m', "'b")),
+ new MTest ("-char='", new MErr('m', "'")),
+ new MTest ("-char=a'", new MErr('m', "a'")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-char2=%c", ch, 'c', 1, "-char2=",null,"",null);
+ tests = new MTest[]
+ {
+ new MTest ("-char2=a", new Character('a')),
+ new MTest ("-char2='\141'", new Character('\141')),
+ new MTest ("-char2=\141", new Character('\141')),
+ new MTest ("-char2=z", new Character('z')),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-charv3 %cX3", vec,'c',3,"-charv3 ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-charv3 a b c", new char[] {'a', 'b', 'c'}, 0),
+ new MTest ("-charv3 'g' f '\\n'", new char[]{'g','f','\n'}, 1),
+ new MTest ("-charv3 1 \001 3", new char[] {'1', '\001', '3'}, 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+ test.checkAdd ("-charv=%c", vec,'c',1,"-charv=",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-charv=d", new Character('d'), 0),
+ new MTest ("-charv='g'", new Character('g'), 1),
+ new MTest ("-charv=\111", new Character('\111'), 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-bool=%b{true}", bh, 'b', 1, "-bool=",
+ new RngCheck[]
+ { new RngCheck (true),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-bool=true", new Boolean(true)),
+ new MTest ("-bool=false", new MErr('r', "false")),
+ new MTest ("-bool=fals", new MErr('m', "fals")),
+ new MTest ("-bool=falsem", new MErr('m', "falsem")),
+ new MTest ("-bool=truex", new MErr('m', "truex")),
+ new MTest ("-bool=foo", new MErr('m', "foo")),
+ new MTest ("-bool=1", new MErr('m', "1")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-boo2=%b{true,false}", bh, 'b', 1, "-boo2=",
+ new RngCheck[]
+ { new RngCheck (true),
+ new RngCheck (false),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-boo2=true", new Boolean(true)),
+ new MTest ("-boo2=false", new Boolean(false)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-boo3=%b", bh, 'b', 1, "-boo3=", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-boo3=true", new Boolean(true)),
+ new MTest ("-boo3=false", new Boolean(false)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-boo3 %bX3", b3, 'b', 3, "-boo3 ", null, "", null);
+ tests = new MTest[]
+ {
+ new MTest ("-boo3 true false true",
+ new boolean[] { true, false, true }),
+ new MTest ("-boo3 true fals true", new MErr ('m', "fals")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd ("-boov3 %bX3", vec,'b',3,"-boov3 ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-boov3 true true false",
+ new boolean [] { true, true, false }, 0),
+ new MTest ("-boov3 false false true",
+ new boolean [] { false, false, true }, 1),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+ test.checkAdd ("-boov %b", vec,'b',1,"-boov ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-boov true", new Boolean (true), 0),
+ new MTest ("-boov false", new Boolean (false), 1),
+ new MTest ("-boov true", new Boolean (true), 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+
+
+ test.checkAdd ("-v3 %vX2", b3, 'v', 2, "-v3 ", null, "", null);
+ tests = new MTest[]
+ { new MTest ("-v3", new boolean[] { true, true }),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-vf %v{false,true}X2", b3, 'v', 2, "-vf ",
+ new RngCheck[]
+ { new RngCheck(false),
+ new RngCheck(true),
+ },
+ "", null);
+ tests = new MTest[]
+ { new MTest ("-vf", new boolean[] { false, false }),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd (
+ "-str=%s{(john,zzzz]}", sh, 's', 1, "-str=",
+ new RngCheck[]
+ { new RngCheck ("john", OPEN, "zzzz", CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-str=john", new MErr ('r', "john")),
+ new MTest ("-str=joho ", "joho "),
+ new MTest ("-str=joho ", "joho "),
+ new MTest ("-str=zzzz", "zzzz"),
+ new MTest ("-str= joho", new MErr ('r', " joho")),
+ new MTest ("-str=jnhn ", new MErr ('r', "jnhn ")),
+ new MTest ("-str=zzzzz", new MErr ('r', "zzzzz")),
+ new MTest ("-str=\"joho\"", new MErr ('r', "\"joho\"")),
+ new MTest ("-str=\"joho", new MErr('r', "\"joho")),
+ new MTest ("-str=joho j", "joho j"), // new MErr('m', "joho j")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-str2=%s", sh,'s',1,"-str2=",null,"",null);
+ tests = new MTest[]
+ {
+ new MTest ("-str2= jnhn", " jnhn"),
+ new MTest ("-str2=zzzzz", "zzzzz"),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-str3 %sX3",s3,'s',3,"-str3 ",null,"",null);
+ tests = new MTest[]
+ {
+ new MTest ("-str3 foo bar johnny",
+ new String[] { "foo", "bar", "johnny" }),
+ new MTest ("-str3 zzzzz \"bad foo",
+ new String[] { "zzzzz", "\"bad", "foo"
+ }), // new MErr('m', "\"bad")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd ("-strv3 %sX3", vec,'s',3,"-strv3 ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-strv3 foo bar \"hihi\"",
+ new String[] {"foo", "bar", "\"hihi\""}, 0),
+ new MTest ("-strv3 a 123 gg",
+ new String[]{"a", "123", "gg"}, 1),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+ test.checkAdd ("-strv=%s", vec,'s',1,"-strv=",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-strv=d", "d", 0),
+ new MTest ("-strv='g'", "'g'", 1),
+ new MTest ("-strv=\\111", "\\111", 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd (
+ "-float=%f{(-0.001,1000.0]}", dh, 'f', 1, "-float=",
+ new RngCheck[]
+ { new RngCheck (-0.001, OPEN, 1000.0, CLOSED),
+ },
+ "", null);
+
+ tests = new MTest[]
+ {
+ new MTest ("-float=-0.000999", new Double(-0.000999)),
+ new MTest ("-float=1e-3", new Double(0.001)),
+ new MTest ("-float=12.33e1", new Double(123.3)),
+ new MTest ("-float=1e3", new Double(1e3)),
+ new MTest ("-float=1000.000", new Double(1000.0)),
+ new MTest ("-float=-0.001", new MErr('r', "-0.001")),
+ new MTest ("-float=-1e-3", new MErr('r', "-1e-3")),
+ new MTest ("-float=1000.001", new MErr('r', "1000.001")),
+ new MTest ("-float=.", new MErr('m', ".")),
+ new MTest ("-float= 124.5 ", new Double (124.5)),
+ new MTest ("-float=124.5x", new MErr('m', "124.5x")),
+ new MTest ("-float= foo ", new MErr('m', " foo ")),
+ new MTest ("-float=1e1", new Double(10)),
+ new MTest ("-float=1e ", new MErr('m', "1e ")),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-float2=%f", dh,'f',1,"-float2=",null,"",null);
+ tests = new MTest[]
+ {
+ new MTest ("-float2=-0.001", new Double(-0.001)),
+ new MTest ("-float2=-1e-3", new Double(-1e-3)),
+ new MTest ("-float2=1000.001", new Double(1000.001)),
+ };
+ test.checkMatches (tests, ONE_WORD);
+
+ test.checkAdd ("-f3 %fX3", d3,'f',3,"-f3 ",null,"",null);
+ tests = new MTest[]
+ {
+ new MTest ("-f3 -0.001 1.23e5 -9.88e-4",
+ new double[] { -0.001, 1.23e5, -9.88e-4 }),
+ new MTest ("-f3 7.88 foo 9.0", new MErr ('m', "foo")),
+ new MTest ("-f3 7.88 . 9.0", new MErr ('m', ".")),
+ new MTest ("-f3 7.88 3.0 9.0x", new MErr ('m', "9.0x")),
+ };
+ test.checkMatches (tests, MULTI_WORD);
+
+ test.checkAdd ("-fv3 %fX3", vec,'f',3,"-fv3 ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-fv3 1.0 3.444 6.7",
+ new double[] {1.0, 3.444, 6.7}, 0),
+ new MTest ("-fv3 13e-5 145.678 0.0001e45",
+ new double[]{13e-5, 145.678, 0.0001e45}, 1),
+ new MTest ("-fv3 11.11 3.1245 -1e-4",
+ new double[] {11.11, 3.1245, -1e-4}, 2),
+ new MTest ("-fv3 1.0 2 3",
+ new double[] { 1.0, 2.0, 3.0 }, 3),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+ test.checkAdd ("-fv %f", vec,'f',1,"-fv ",null,"",null);
+ tests = new MTest[]
+ { new MTest ("-fv -15.1234", new Double(-15.1234), 0),
+ new MTest ("-fv -1.234e-7", new Double(-1.234e-7), 1),
+ new MTest ("-fv 0.001111", new Double(0.001111), 2),
+ };
+ vec.clear();
+ test.checkMatches (tests, MULTI_WORD);
+
+
+ IntHolder intHolder = new IntHolder();
+ StringHolder strHolder = new StringHolder();
+
+ ArgParser parser = new ArgParser ("test");
+ parser.addOption ("-foo %d #an int", intHolder);
+ parser.addOption ("-bar %s #a string", strHolder);
+ args = new String[]
+ { "zzz", "-cat", "-foo", "123", "yyy", "-bar", "xxxx", "xxx"
+ };
+
+ String[] unmatchedCheck = new String[]
+ { "zzz", "-cat", "yyy", "xxx"
+ };
+
+ String[] unmatched = parser.matchAllArgs (args, 0, 0);
+ test.checkStringArray (
+ "Unmatched args:", unmatched, unmatchedCheck);
+
+ vec.clear();
+ for (int i=0; i<args.length; )
+ { try
+ { i = parser.matchArg (args, i);
+ if (parser.getUnmatchedArgument() != null)
+ { vec.add (parser.getUnmatchedArgument());
+ }
+ }
+ catch (Exception e)
+ {
+ }
+ }
+ unmatched = (String[])vec.toArray(new String[0]);
+ test.checkStringArray (
+ "My unmatched args:", unmatched, unmatchedCheck);
+
+ System.out.println ("\nPassed\n");
+
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
index dba72b6d..c5dece11 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,34 +18,37 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a boolean value, enabling methods to return
- * boolean values through arguments.
- */
-public class BooleanHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a boolean value,
+ * enabling methods to return boolean values through
+ * arguments.
+ */
+public class BooleanHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = -2863748864787121510L;
/**
- * Value of the boolean, set and examined by the application as needed.
- */
- public boolean value;
+ * Value of the boolean, set and examined
+ * by the application as needed.
+ */
+ public boolean value;
- /**
- * Constructs a new <code>BooleanHolder</code> with an initial value of
- * <code>false</code>.
- */
- public BooleanHolder() {
- value = false;
- }
+ /**
+ * Constructs a new <code>BooleanHolder</code> with an initial
+ * value of <code>false</code>.
+ */
+ public BooleanHolder ()
+ { value = false;
+ }
- /**
- * Constructs a new <code>BooleanHolder</code> with a specific initial
- * value.
- *
- * @param b Initial boolean value.
- */
- public BooleanHolder(boolean b) {
- value = b;
- }
+ /**
+ * Constructs a new <code>BooleanHolder</code> with a
+ * specific initial value.
+ *
+ * @param b Initial boolean value.
+ */
+ public BooleanHolder (boolean b)
+ { value = b;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
index eed57892..b30259b4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,32 +18,39 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a character value, enabling methods to return
- * character values through arguments.
- */
-public class CharHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a character value,
+ * enabling methods to return character values through
+ * arguments.
+ */
+public class CharHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = 7340010668929015745L;
/**
- * Value of the character, set and examined by the application as needed.
- */
- public char value;
+ * Value of the character, set and examined
+ * by the application as needed.
+ */
+ public char value;
- /**
- * Constructs a new <code>CharHolder</code> with an initial value of 0.
- */
- public CharHolder() {
- value = 0;
- }
+ /**
+ * Constructs a new <code>CharHolder</code> with an initial
+ * value of 0.
+ */
+ public CharHolder ()
+ { value = 0;
+ }
- /**
- * Constructs a new <code>CharHolder</code> with a specific initial value.
- *
- * @param c Initial character value.
- */
- public CharHolder(char c) {
- value = c;
- }
+ /**
+ * Constructs a new <code>CharHolder</code> with a
+ * specific initial value.
+ *
+ * @param c Initial character value.
+ */
+ public CharHolder (char c)
+ { value = c;
+ }
}
+
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
index b75f9f15..293a9cc7 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,32 +18,38 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a double value, enabling methods to return
- * double values through arguments.
- */
-public class DoubleHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a double value,
+ * enabling methods to return double values through
+ * arguments.
+ */
+public class DoubleHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = 5461991811517552431L;
/**
- * Value of the double, set and examined by the application as needed.
- */
- public double value;
+ * Value of the double, set and examined
+ * by the application as needed.
+ */
+ public double value;
- /**
- * Constructs a new <code>DoubleHolder</code> with an initial value of 0.
- */
- public DoubleHolder() {
- value = 0;
- }
+ /**
+ * Constructs a new <code>DoubleHolder</code> with an initial
+ * value of 0.
+ */
+ public DoubleHolder ()
+ { value = 0;
+ }
- /**
- * Constructs a new <code>DoubleHolder</code> with a specific initial value.
- *
- * @param d Initial double value.
- */
- public DoubleHolder(double d) {
- value = d;
- }
+ /**
+ * Constructs a new <code>DoubleHolder</code> with a
+ * specific initial value.
+ *
+ * @param d Initial double value.
+ */
+ public DoubleHolder (double d)
+ { value = d;
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
index 14a13d9e..0fbcc45a 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,32 +18,39 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a float value, enabling methods to return float
- * values through arguments.
- */
-public class FloatHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a float value,
+ * enabling methods to return float values through
+ * arguments.
+ */
+public class FloatHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = -7962968109874934361L;
/**
- * Value of the float, set and examined by the application as needed.
- */
- public float value;
+ * Value of the float, set and examined
+ * by the application as needed.
+ */
+ public float value;
- /**
- * Constructs a new <code>FloatHolder</code> with an initial value of 0.
- */
- public FloatHolder() {
- value = 0;
- }
+ /**
+ * Constructs a new <code>FloatHolder</code> with an initial
+ * value of 0.
+ */
+ public FloatHolder ()
+ { value = 0;
+ }
- /**
- * Constructs a new <code>FloatHolder</code> with a specific initial value.
- *
- * @param f Initial float value.
- */
- public FloatHolder(float f) {
- value = f;
- }
+ /**
+ * Constructs a new <code>FloatHolder</code> with a
+ * specific initial value.
+ *
+ * @param f Initial float value.
+ */
+ public FloatHolder (float f)
+ { value = f;
+ }
}
+
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
index 446af9eb..efd6d1bf 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,32 +18,38 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' an integer value, enabling methods to return
- * integer values through arguments.
- */
-public class IntHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' an integer value,
+ * enabling methods to return integer values through
+ * arguments.
+ */
+public class IntHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = -5303361328570056819L;
/**
- * Value of the integer, set and examined by the application as needed.
- */
- public int value;
+ * Value of the integer, set and examined
+ * by the application as needed.
+ */
+ public int value;
- /**
- * Constructs a new <code>IntHolder</code> with an initial value of 0.
- */
- public IntHolder() {
- value = 0;
- }
+ /**
+ * Constructs a new <code>IntHolder</code> with an initial
+ * value of 0.
+ */
+ public IntHolder ()
+ { value = 0;
+ }
- /**
- * Constructs a new <code>IntHolder</code> with a specific initial value.
- *
- * @param i Initial integer value.
- */
- public IntHolder(int i) {
- value = i;
- }
+ /**
+ * Constructs a new <code>IntHolder</code> with a
+ * specific initial value.
+ *
+ * @param i Initial integer value.
+ */
+ public IntHolder (int i)
+ { value = i;
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
index 37aa1c91..84752d60 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,32 +18,38 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a long value, enabling methods to return long
- * values through arguments.
- */
-public class LongHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a long value,
+ * enabling methods to return long values through
+ * arguments.
+ */
+public class LongHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = 1559599139421340971L;
/**
- * Value of the long, set and examined by the application as needed.
- */
- public long value;
+ * Value of the long, set and examined
+ * by the application as needed.
+ */
+ public long value;
- /**
- * Constructs a new <code>LongHolder</code> with an initial value of 0.
- */
- public LongHolder() {
- value = 0;
- }
+ /**
+ * Constructs a new <code>LongHolder</code> with an initial
+ * value of 0.
+ */
+ public LongHolder ()
+ { value = 0;
+ }
- /**
- * Constructs a new <code>LongHolder</code> with a specific initial value.
- *
- * @param l Initial long value.
- */
- public LongHolder(long l) {
- value = l;
- }
+ /**
+ * Constructs a new <code>LongHolder</code> with a
+ * specific initial value.
+ *
+ * @param l Initial long value.
+ */
+ public LongHolder (long l)
+ { value = l;
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
index edb835ee..cc8361d9 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,34 +18,37 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' an Object reference, enabling methods to return
- * Object references through arguments.
- */
-public class ObjectHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' an Object reference,
+ * enabling methods to return Object references through
+ * arguments.
+ */
+public class ObjectHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = 1825881254530066307L;
/**
- * Value of the Object reference, set and examined by the application as
- * needed.
- */
- public Object value;
+ * Value of the Object reference, set and examined
+ * by the application as needed.
+ */
+ public Object value;
- /**
- * Constructs a new <code>ObjectHolder</code> with an initial value of
- * <code>null</code>.
- */
- public ObjectHolder() {
- value = null;
- }
+ /**
+ * Constructs a new <code>ObjectHolder</code> with an initial
+ * value of <code>null</code>.
+ */
+ public ObjectHolder ()
+ { value = null;
+ }
- /**
- * Constructs a new <code>ObjectHolder</code> with a specific initial value.
- *
- * @param o Initial Object reference.
- */
- public ObjectHolder(Object o) {
- value = o;
- }
+ /**
+ * Constructs a new <code>ObjectHolder</code> with a
+ * specific initial value.
+ *
+ * @param o Initial Object reference.
+ */
+ public ObjectHolder (Object o)
+ { value = o;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
index 21e05606..8086131b 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,35 +18,39 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Gives a very simple example of the use of {@link argparser.ArgParser
- * ArgParser}.
+ * Gives a very simple example of the use of
+ * {@link argparser.ArgParser ArgParser}.
*/
-public class SimpleExample {
- /**
- * Run this to invoke command line parsing.
- */
- public static void main(String[] args) {
- // create holder objects for storing results ...
-
- DoubleHolder theta = new DoubleHolder();
- StringHolder fileName = new StringHolder();
- BooleanHolder debug = new BooleanHolder();
-
- // create the parser and specify the allowed options ...
-
- ArgParser parser = new ArgParser("java argparser.SimpleExample");
- parser.addOption("-theta %f #theta value (in degrees)", theta);
- parser.addOption("-file %s #name of the operating file", fileName);
- parser.addOption("-debug %v #enables display of debugging info", debug);
-
- // and then match the arguments
-
- parser.matchAllArgs(args);
-
- // now print out the values
-
- System.out.println("theta=" + theta.value);
- System.out.println("fileName=" + fileName.value);
- System.out.println("debug=" + debug.value);
- }
+public class SimpleExample
+{
+ /**
+ * Run this to invoke command line parsing.
+ */
+ public static void main (String[] args)
+ {
+ // create holder objects for storing results ...
+
+ DoubleHolder theta = new DoubleHolder();
+ StringHolder fileName = new StringHolder();
+ BooleanHolder debug = new BooleanHolder();
+
+ // create the parser and specify the allowed options ...
+
+ ArgParser parser = new ArgParser("java argparser.SimpleExample");
+ parser.addOption ("-theta %f #theta value (in degrees)", theta);
+ parser.addOption ("-file %s #name of the operating file", fileName);
+ parser.addOption ("-debug %v #enables display of debugging info",
+ debug);
+
+ // and then match the arguments
+
+ parser.matchAllArgs (args);
+
+ // now print out the values
+
+ System.out.println ("theta=" + theta.value);
+ System.out.println ("fileName=" + fileName.value);
+ System.out.println ("debug=" + debug.value);
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
index ea85c7d0..9b41b6a2 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,34 +18,38 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Wrapper class which ``holds'' a String reference, enabling methods to return
- * String references through arguments.
- */
-public class StringHolder implements java.io.Serializable {
- /**
+ * Wrapper class which ``holds'' a String reference,
+ * enabling methods to return String references through
+ * arguments.
+ */
+public class StringHolder implements java.io.Serializable
+{
+ /**
*
*/
private static final long serialVersionUID = -3184348746223759310L;
/**
- * Value of the String reference, set and examined by the application as
- * needed.
- */
- public String value;
+ * Value of the String reference, set and examined
+ * by the application as needed.
+ */
+ public String value;
- /**
- * Constructs a new <code>StringHolder</code> with an initial value of
- * <code>null</code>.
- */
- public StringHolder() {
- value = null;
- }
+ /**
+ * Constructs a new <code>StringHolder</code> with an
+ * initial value of <code>null</code>.
+ */
+ public StringHolder ()
+ { value = null;
+ }
- /**
- * Constructs a new <code>StringHolder</code> with a specific initial value.
- *
- * @param s Initial String reference.
- */
- public StringHolder(String s) {
- value = s;
- }
+ /**
+ * Constructs a new <code>StringHolder</code> with a
+ * specific initial value.
+ *
+ * @param s Initial String reference.
+ */
+ public StringHolder (String s)
+ { value = s;
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
index 9d942f0d..4b71a0f2 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -20,37 +19,40 @@ package com.netscape.pkisilent.argparser;
import java.io.IOException;
-/**
- * Exception class used by <code>StringScanner</code> when command line
- * arguments do not parse correctly.
- *
- * @author John E. Lloyd, Winter 2001
- * @see StringScanner
- */
-class StringScanException extends IOException {
- /**
+/**
+ * Exception class used by <code>StringScanner</code> when
+ * command line arguments do not parse correctly.
+ *
+ * @author John E. Lloyd, Winter 2001
+ * @see StringScanner
+ */
+class StringScanException extends IOException
+{
+ /**
*
*/
private static final long serialVersionUID = 4923445904507805754L;
int failIdx;
- /**
- * Creates a new StringScanException with the given message.
- *
- * @param msg Error message
- * @see StringScanner
- */
+ /**
+ * Creates a new StringScanException with the given message.
+ *
+ * @param msg Error message
+ * @see StringScanner
+ */
- public StringScanException(String msg) {
- super(msg);
- }
+ public StringScanException (String msg)
+ { super (msg);
+ }
- public StringScanException(int idx, String msg) {
- super(msg);
- failIdx = idx;
- }
+ public StringScanException (int idx, String msg)
+ {
+ super (msg);
+ failIdx = idx;
+ }
- public int getFailIndex() {
- return failIdx;
- }
+ public int getFailIndex()
+ {
+ return failIdx;
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
index 77d73652..fae67c79 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.argparser;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -19,542 +18,634 @@ package com.netscape.pkisilent.argparser;
// --- END COPYRIGHT BLOCK ---
/**
- * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use, copy,
- * modify and redistribute is granted, provided that this copyright notice is
- * retained and the author is given credit whenever appropriate.
- *
- * This software is distributed "as is", without any warranty, including any
- * implied warranty of merchantability or fitness for a particular use. The
- * author assumes no responsibility for, and shall not be liable for, any
- * special, indirect, or consequential damages, or any damages whatsoever,
- * arising out of or in connection with the use of this software.
- */
-
-class StringScanner {
- private char[] buf;
- private int idx;
- private int len;
- private String stringDelimiters = "";
-
- public StringScanner(String s) {
- buf = new char[s.length() + 1];
- s.getChars(0, s.length(), buf, 0);
- len = s.length();
- buf[len] = 0;
- idx = 0;
- }
-
- public int getIndex() {
- return idx;
- }
-
- public void setIndex(int i) {
- if (i < 0) {
- idx = 0;
- } else if (i > len) {
- idx = len;
- } else {
- idx = i;
- }
- }
-
- public void setStringDelimiters(String s) {
- stringDelimiters = s;
- }
-
- public String getStringDelimiters() {
- return stringDelimiters;
- }
-
- public char scanChar() throws StringScanException {
- int idxSave = idx;
- skipWhiteSpace();
- try {
- if (buf[idx] == '\'') {
- return scanQuotedChar();
- } else {
- return scanUnquotedChar();
- }
- } catch (StringScanException e) {
- idx = idxSave;
- throw e;
- }
- }
-
- public char scanQuotedChar() throws StringScanException {
- StringScanException exception = null;
- char retval = 0;
- int idxSave = idx;
-
- skipWhiteSpace();
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else if (buf[idx++] == '\'') {
- try {
- retval = scanUnquotedChar();
- } catch (StringScanException e) {
- exception = e;
- }
- if (exception == null) {
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else if (buf[idx++] != '\'') {
- exception = new StringScanException(idx - 1,
- "unclosed quoted character");
- }
- }
- } else {
- exception = new StringScanException(idx - 1,
- "uninitialized quoted character");
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return retval;
- }
-
- public char scanUnquotedChar() throws StringScanException {
- StringScanException exception = null;
- char c, retval = 0;
- int idxSave = idx;
-
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else if ((c = buf[idx++]) == '\\') {
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else {
- c = buf[idx++];
- if (c == '"') {
- retval = '"';
- } else if (c == '\'') {
- retval = '\'';
- } else if (c == '\\') {
- retval = '\\';
- } else if (c == 'n') {
- retval = '\n';
- } else if (c == 't') {
- retval = '\t';
- } else if (c == 'b') {
- retval = '\b';
- } else if (c == 'r') {
- retval = '\r';
- } else if (c == 'f') {
- retval = '\f';
- } else if ('0' <= c && c < '8') {
- int v = c - '0';
- for (int j = 0; j < 2; j++) {
- if (idx == len) {
- break;
- }
- c = buf[idx];
- if ('0' <= c && c < '8' && (v * 8 + (c - '0')) <= 255) {
- v = v * 8 + (c - '0');
- idx++;
- } else {
- break;
- }
- }
- retval = (char) v;
- } else {
- exception = new StringScanException(idx - 1,
- "illegal escape character '" + c + "'");
- }
- }
- } else {
- retval = c;
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return retval;
- }
-
- public String scanQuotedString() throws StringScanException {
- StringScanException exception = null;
- StringBuffer sbuf = new StringBuffer(len);
- char c;
- int idxSave = idx;
-
- skipWhiteSpace();
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else if ((c = buf[idx++]) == '"') {
- while (idx < len && (c = buf[idx]) != '"' && c != '\n') {
- if (c == '\\') {
- try {
- c = scanUnquotedChar();
- } catch (StringScanException e) {
- exception = e;
- break;
- }
- } else {
- idx++;
- }
- sbuf.append(c);
- }
- if (exception == null && idx >= len) {
- exception = new StringScanException(len, "end of input");
- } else if (exception == null && c == '\n') {
- exception = new StringScanException(idx,
- "unclosed quoted string");
- } else {
- idx++;
- }
- } else {
- exception = new StringScanException(idx - 1,
- "quoted string must start with \"");
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return sbuf.toString();
- }
-
- public String scanNonWhiteSpaceString() throws StringScanException {
- StringBuffer sbuf = new StringBuffer(len);
- int idxSave = idx;
- char c;
-
- skipWhiteSpace();
- if (idx == len) {
- StringScanException e = new StringScanException(idx, "end of input");
- idx = idxSave;
- throw e;
- } else {
- c = buf[idx++];
- while (idx < len && !Character.isWhitespace(c)
- && stringDelimiters.indexOf(c) == -1) {
- sbuf.append(c);
- c = buf[idx++];
- }
- if (Character.isWhitespace(c) || stringDelimiters.indexOf(c) != -1) {
- idx--;
- } else {
- sbuf.append(c);
- }
- }
- return sbuf.toString();
- }
-
- public String scanString() throws StringScanException {
- int idxSave = idx;
- skipWhiteSpace();
- try {
- if (buf[idx] == '"') {
- return scanQuotedString();
- } else {
- return scanNonWhiteSpaceString();
- }
- } catch (StringScanException e) {
- idx = idxSave;
- throw e;
- }
- }
-
- public String getString() throws StringScanException {
- StringBuffer sbuf = new StringBuffer(len);
- while (idx < len) {
- sbuf.append(buf[idx++]);
- }
- return sbuf.toString();
- }
-
- public long scanInt() throws StringScanException {
- int idxSave = idx;
- char c;
- int sign = 1;
-
- skipWhiteSpace();
- if ((c = buf[idx]) == '-' || c == '+') {
- sign = (c == '-' ? -1 : 1);
- idx++;
- }
- try {
- if (idx == len) {
- throw new StringScanException(len, "end of input");
- } else if ((c = buf[idx]) == '0') {
- if ((c = buf[idx + 1]) == 'x' || c == 'X') {
- idx += 2;
- return sign * scanInt(16, false);
- } else {
- return sign * scanInt(8, false);
- }
- } else {
- return sign * scanInt(10, false);
- }
- } catch (StringScanException e) {
- idx = idxSave;
- throw e;
- }
- }
-
- public long scanInt(int radix) throws StringScanException {
- return scanInt(radix, /* skipWhite= */true);
- }
-
- private String baseDesc(int radix) {
- switch (radix) {
- case 10: {
- return "decimal";
- }
- case 8: {
- return "octal";
- }
- case 16: {
- return "hex";
- }
- default: {
- return "base " + radix;
- }
- }
- }
-
- public long scanInt(int radix, boolean skipWhite)
- throws StringScanException {
- StringScanException exception = null;
- int charval, idxSave = idx;
- char c;
- long val = 0;
- boolean negate = false;
-
- if (skipWhite) {
- skipWhiteSpace();
- }
- if ((c = buf[idx]) == '-' || c == '+') {
- negate = (c == '-');
- idx++;
- }
- if (idx >= len) {
- exception = new StringScanException(len, "end of input");
- } else if ((charval = Character.digit(buf[idx++], radix)) == -1) {
- exception = new StringScanException(idx - 1, "malformed "
- + baseDesc(radix) + " integer");
- } else {
- val = charval;
- while ((charval = Character.digit(buf[idx], radix)) != -1) {
- val = val * radix + charval;
- idx++;
- }
- if (Character.isLetter(c = buf[idx]) || Character.isDigit(c)
- || c == '_') {
- exception = new StringScanException(idx, "malformed "
- + baseDesc(radix) + " integer");
- }
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return negate ? -val : val;
- }
-
- public double scanDouble() throws StringScanException {
- StringScanException exception = null;
- int idxSave = idx;
- char c;
- // parse [-][0-9]*[.][0-9]*[eE][-][0-9]*
- boolean hasDigits = false;
- boolean signed;
- double value = 0;
-
- skipWhiteSpace();
- if (idx == len) {
- exception = new StringScanException("end of input");
- } else {
- if ((c = buf[idx]) == '-' || c == '+') {
- signed = true;
- idx++;
- }
- if (matchDigits()) {
- hasDigits = true;
- }
- if (buf[idx] == '.') {
- idx++;
- }
- if (!hasDigits && (buf[idx] < '0' || buf[idx] > '9')) {
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- } else {
- exception = new StringScanException(idx,
- "malformed floating number: no digits");
- }
- } else {
- matchDigits();
-
- if ((c = buf[idx]) == 'e' || c == 'E') {
- idx++;
- if ((c = buf[idx]) == '-' || c == '+') {
- signed = true;
- idx++;
- }
- if (buf[idx] < '0' || buf[idx] > '9') {
- if (idx == len) {
- exception = new StringScanException(idx,
- "end of input");
- } else {
- exception = new StringScanException(idx,
- "malformed floating number: no digits in exponent");
- }
- } else {
- matchDigits();
- }
- }
- }
- }
- if (exception == null) {
- // if (Character.isLetterOrDigit(c=buf[idx]) || c == '_')
- // { exception = new StringScanException (idx,
- // "malformed floating number");
- // }
- // else
- {
- try {
- value = Double.parseDouble(new String(buf, idxSave, idx
- - idxSave));
- } catch (NumberFormatException e) {
- exception = new StringScanException(idx,
- "malformed floating number");
- }
- }
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return value;
- }
-
- public boolean scanBoolean() throws StringScanException {
- StringScanException exception = null;
- int idxSave = idx;
- String testStr = "false";
- boolean testval = false;
- char c;
-
- skipWhiteSpace();
- if (buf[idx] == 't') {
- testStr = "true";
- testval = true;
- } else {
- testval = false;
- }
- int i = 0;
- for (i = 0; i < testStr.length(); i++) {
- if (testStr.charAt(i) != buf[idx]) {
- if (idx == len) {
- exception = new StringScanException(idx, "end of input");
- }
- break;
- }
- idx++;
- }
- if (exception == null) {
- if (i < testStr.length() || Character.isLetterOrDigit(c = buf[idx])
- || c == '_') {
- exception = new StringScanException(idx, "illegal boolean");
- }
- }
- if (exception != null) {
- idx = idxSave;
- throw exception;
- }
- return testval;
- }
-
- public boolean matchString(String s) {
- int k = idx;
- for (int i = 0; i < s.length(); i++) {
- if (k >= len || s.charAt(i) != buf[k++]) {
- return false;
- }
- }
- idx = k;
- return true;
- }
-
- public boolean matchDigits() {
- int k = idx;
- char c;
-
- while ((c = buf[k]) >= '0' && c <= '9') {
- k++;
- }
- if (k > idx) {
- idx = k;
- return true;
- } else {
- return false;
- }
- }
-
- public void skipWhiteSpace() {
- while (Character.isWhitespace(buf[idx])) {
- idx++;
- }
- }
-
- private int skipWhiteSpace(int k) {
- while (Character.isWhitespace(buf[k])) {
- k++;
- }
- return k;
- }
-
- public boolean atEnd() {
- return idx == len;
- }
-
- public boolean atBeginning() {
- return idx == 0;
- }
-
- public void ungetc() {
- if (idx > 0) {
- idx--;
- }
- }
-
- public char getc() {
- char c = buf[idx];
- if (idx < len) {
- idx++;
- }
- return c;
- }
-
- public char peekc() {
- return buf[idx];
- }
-
- public String substring(int i0, int i1) {
- if (i0 < 0) {
- i0 = 0;
- } else if (i0 >= len) {
- i0 = len - 1;
- }
- if (i1 < 0) {
- i1 = 0;
- } else if (i1 > len) {
- i1 = len;
- }
- if (i1 <= i0) {
- return "";
- }
- return new String(buf, i0, i1 - i0);
- }
-
- public String substring(int i0) {
- if (i0 < 0) {
- i0 = 0;
- }
- if (i0 >= len) {
- return "";
- } else {
- return new String(buf, i0, len - i0);
- }
- }
+ * Copyright John E. Lloyd, 2004. All rights reserved. Permission to use,
+ * copy, modify and redistribute is granted, provided that this copyright
+ * notice is retained and the author is given credit whenever appropriate.
+ *
+ * This software is distributed "as is", without any warranty, including
+ * any implied warranty of merchantability or fitness for a particular
+ * use. The author assumes no responsibility for, and shall not be liable
+ * for, any special, indirect, or consequential damages, or any damages
+ * whatsoever, arising out of or in connection with the use of this
+ * software.
+ */
+
+class StringScanner
+{
+ private char[] buf;
+ private int idx;
+ private int len;
+ private String stringDelimiters = "";
+
+ public StringScanner (String s)
+ {
+ buf = new char[s.length()+1];
+ s.getChars (0, s.length(), buf, 0);
+ len = s.length();
+ buf[len] = 0;
+ idx = 0;
+ }
+
+ public int getIndex()
+ { return idx;
+ }
+
+ public void setIndex(int i)
+ { if (i < 0)
+ { idx = 0;
+ }
+ else if (i > len)
+ { idx = len;
+ }
+ else
+ { idx = i;
+ }
+ }
+
+ public void setStringDelimiters (String s)
+ { stringDelimiters = s;
+ }
+
+ public String getStringDelimiters()
+ { return stringDelimiters;
+ }
+
+ public char scanChar ()
+ throws StringScanException
+ {
+ int idxSave = idx;
+ skipWhiteSpace();
+ try
+ { if (buf[idx] == '\'')
+ { return scanQuotedChar();
+ }
+ else
+ { return scanUnquotedChar();
+ }
+ }
+ catch (StringScanException e)
+ { idx = idxSave;
+ throw e;
+ }
+ }
+
+ public char scanQuotedChar ()
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ char retval = 0;
+ int idxSave = idx;
+
+ skipWhiteSpace();
+ if (idx == len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ else if (buf[idx++] == '\'')
+ { try
+ { retval = scanUnquotedChar();
+ }
+ catch (StringScanException e)
+ { exception = e;
+ }
+ if (exception==null)
+ { if (idx==len)
+ { exception = new StringScanException
+ (idx, "end of input");
+ }
+ else if (buf[idx++] != '\'')
+ { exception = new StringScanException
+ (idx-1, "unclosed quoted character");
+ }
+ }
+ }
+ else
+ { exception = new StringScanException
+ (idx-1, "uninitialized quoted character");
+ }
+ if (exception!=null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return retval;
+ }
+
+ public char scanUnquotedChar ()
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ char c, retval = 0;
+ int idxSave = idx;
+
+ if (idx == len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ else if ((c = buf[idx++]) == '\\')
+ { if (idx == len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ else
+ {
+ c = buf[idx++];
+ if (c == '"')
+ { retval = '"';
+ }
+ else if (c == '\'')
+ { retval = '\'';
+ }
+ else if (c == '\\')
+ { retval = '\\';
+ }
+ else if (c == 'n')
+ { retval = '\n';
+ }
+ else if (c == 't')
+ { retval = '\t';
+ }
+ else if (c == 'b')
+ { retval = '\b';
+ }
+ else if (c == 'r')
+ { retval = '\r';
+ }
+ else if (c == 'f')
+ { retval = '\f';
+ }
+ else if ('0' <= c && c < '8')
+ { int v = c - '0';
+ for (int j=0; j<2; j++)
+ { if (idx==len)
+ { break;
+ }
+ c = buf[idx];
+ if ('0' <= c && c < '8' && (v*8 + (c-'0')) <= 255)
+ { v = v*8 + (c-'0');
+ idx++;
+ }
+ else
+ { break;
+ }
+ }
+ retval = (char)v;
+ }
+ else
+ { exception = new StringScanException
+ (idx-1, "illegal escape character '" + c + "'");
+ }
+ }
+ }
+ else
+ { retval = c;
+ }
+ if (exception!=null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return retval;
+ }
+
+ public String scanQuotedString ()
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ StringBuffer sbuf = new StringBuffer(len);
+ char c;
+ int idxSave = idx;
+
+ skipWhiteSpace();
+ if (idx == len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ else if ((c=buf[idx++]) == '"')
+ { while (idx<len && (c=buf[idx]) != '"' && c != '\n')
+ { if (c == '\\')
+ { try
+ { c = scanUnquotedChar();
+ }
+ catch (StringScanException e)
+ { exception = e;
+ break;
+ }
+ }
+ else
+ { idx++;
+ }
+ sbuf.append (c);
+ }
+ if (exception == null && idx>=len)
+ { exception = new StringScanException (len, "end of input");
+ }
+ else if (exception == null && c == '\n')
+ { exception = new StringScanException
+ (idx, "unclosed quoted string");
+ }
+ else
+ { idx++;
+ }
+ }
+ else
+ { exception = new StringScanException (idx-1,
+"quoted string must start with \"");
+ }
+ if (exception != null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return sbuf.toString();
+ }
+
+ public String scanNonWhiteSpaceString()
+ throws StringScanException
+ {
+ StringBuffer sbuf = new StringBuffer(len);
+ int idxSave = idx;
+ char c;
+
+ skipWhiteSpace();
+ if (idx == len)
+ { StringScanException e = new StringScanException (
+ idx, "end of input");
+ idx = idxSave;
+ throw e;
+ }
+ else
+ { c = buf[idx++];
+ while (idx<len && !Character.isWhitespace(c)
+ && stringDelimiters.indexOf(c) == -1)
+ { sbuf.append(c);
+ c = buf[idx++];
+ }
+ if (Character.isWhitespace(c) ||
+ stringDelimiters.indexOf(c) != -1)
+ { idx--;
+ }
+ else
+ { sbuf.append(c);
+ }
+ }
+ return sbuf.toString();
+ }
+
+ public String scanString ()
+ throws StringScanException
+ {
+ int idxSave = idx;
+ skipWhiteSpace();
+ try
+ { if (buf[idx] == '"')
+ { return scanQuotedString();
+ }
+ else
+ { return scanNonWhiteSpaceString();
+ }
+ }
+ catch (StringScanException e)
+ { idx = idxSave;
+ throw e;
+ }
+ }
+
+ public String getString ()
+ throws StringScanException
+ {
+ StringBuffer sbuf = new StringBuffer(len);
+ while (idx < len)
+ { sbuf.append (buf[idx++]);
+ }
+ return sbuf.toString();
+ }
+
+ public long scanInt ()
+ throws StringScanException
+ {
+ int idxSave = idx;
+ char c;
+ int sign = 1;
+
+ skipWhiteSpace();
+ if ((c=buf[idx]) == '-' || c == '+')
+ { sign = (c == '-' ? -1 : 1);
+ idx++;
+ }
+ try
+ { if (idx==len)
+ { throw new StringScanException (len, "end of input");
+ }
+ else if ((c=buf[idx]) == '0')
+ { if ((c=buf[idx+1]) == 'x' || c == 'X')
+ { idx += 2;
+ return sign*scanInt (16, false);
+ }
+ else
+ { return sign*scanInt (8, false);
+ }
+ }
+ else
+ { return sign*scanInt (10, false);
+ }
+ }
+ catch (StringScanException e)
+ { idx = idxSave;
+ throw e;
+ }
+ }
+
+ public long scanInt (int radix)
+ throws StringScanException
+ {
+ return scanInt (radix, /*skipWhite=*/true);
+ }
+
+ private String baseDesc (int radix)
+ {
+ switch (radix)
+ { case 10:
+ { return "decimal";
+ }
+ case 8:
+ { return "octal";
+ }
+ case 16:
+ { return "hex";
+ }
+ default:
+ { return "base " + radix;
+ }
+ }
+ }
+
+ public long scanInt (int radix, boolean skipWhite)
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ int charval, idxSave = idx;
+ char c;
+ long val = 0;
+ boolean negate = false;
+
+ if (skipWhite)
+ { skipWhiteSpace();
+ }
+ if ((c=buf[idx]) == '-' || c == '+')
+ { negate = (c == '-');
+ idx++;
+ }
+ if (idx >= len)
+ { exception = new StringScanException (len, "end of input");
+ }
+ else if ((charval=Character.digit(buf[idx++],radix)) == -1)
+ { exception = new StringScanException
+ (idx-1, "malformed " + baseDesc(radix) + " integer");
+ }
+ else
+ { val = charval;
+ while ((charval=Character.digit(buf[idx],radix)) != -1)
+ { val = val*radix + charval;
+ idx++;
+ }
+ if (Character.isLetter(c=buf[idx]) ||
+ Character.isDigit(c) || c == '_')
+ { exception = new StringScanException
+ (idx, "malformed " + baseDesc(radix) + " integer");
+ }
+ }
+ if (exception != null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return negate ? -val : val;
+ }
+
+ public double scanDouble ()
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ int idxSave = idx;
+ char c;
+ // parse [-][0-9]*[.][0-9]*[eE][-][0-9]*
+ boolean hasDigits = false;
+ boolean signed;
+ double value = 0;
+
+ skipWhiteSpace();
+ if (idx == len)
+ { exception = new StringScanException ("end of input");
+ }
+ else
+ {
+ if ((c=buf[idx]) == '-' || c == '+')
+ { signed = true;
+ idx++;
+ }
+ if (matchDigits())
+ { hasDigits = true;
+ }
+ if (buf[idx] == '.')
+ { idx++;
+ }
+ if (!hasDigits && (buf[idx] < '0' || buf[idx] > '9'))
+ { if (idx==len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ else
+ { exception = new StringScanException (
+ idx, "malformed floating number: no digits");
+ }
+ }
+ else
+ { matchDigits();
+
+ if ((c=buf[idx]) == 'e' || c == 'E')
+ { idx++;
+ if ((c=buf[idx]) == '-' || c == '+')
+ { signed = true;
+ idx++;
+ }
+ if (buf[idx] < '0' || buf[idx] > '9')
+ { if (idx==len)
+ { exception = new StringScanException(
+ idx, "end of input");
+ }
+ else
+ { exception = new StringScanException (idx,
+"malformed floating number: no digits in exponent");
+ }
+ }
+ else
+ { matchDigits();
+ }
+ }
+ }
+ }
+ if (exception == null)
+ {
+// if (Character.isLetterOrDigit(c=buf[idx]) || c == '_')
+// { exception = new StringScanException (idx,
+//"malformed floating number");
+// }
+// else
+ {
+ try
+ { value = Double.parseDouble(new String(buf, idxSave,
+ idx-idxSave));
+ }
+ catch (NumberFormatException e)
+ { exception = new StringScanException (
+ idx, "malformed floating number");
+ }
+ }
+ }
+ if (exception != null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return value;
+ }
+
+ public boolean scanBoolean ()
+ throws StringScanException
+ {
+ StringScanException exception = null;
+ int idxSave = idx;
+ String testStr = "false";
+ boolean testval = false;
+ char c;
+
+ skipWhiteSpace();
+ if (buf[idx] == 't')
+ { testStr = "true";
+ testval = true;
+ }
+ else
+ { testval = false;
+ }
+ int i = 0;
+ for (i=0; i<testStr.length(); i++)
+ { if (testStr.charAt(i) != buf[idx])
+ { if (idx==len)
+ { exception = new StringScanException (idx, "end of input");
+ }
+ break;
+ }
+ idx++;
+ }
+ if (exception==null)
+ { if (i<testStr.length() ||
+ Character.isLetterOrDigit(c=buf[idx]) || c == '_')
+ { exception = new StringScanException (idx, "illegal boolean");
+ }
+ }
+ if (exception != null)
+ { idx = idxSave;
+ throw exception;
+ }
+ return testval;
+ }
+
+ public boolean matchString (String s)
+ {
+ int k = idx;
+ for (int i=0; i<s.length(); i++)
+ { if (k >= len || s.charAt(i) != buf[k++])
+ { return false;
+ }
+ }
+ idx = k;
+ return true;
+ }
+
+ public boolean matchDigits ()
+ {
+ int k = idx;
+ char c;
+
+ while ((c=buf[k]) >= '0' && c <= '9')
+ { k++;
+ }
+ if (k > idx)
+ { idx = k;
+ return true;
+ }
+ else
+ { return false;
+ }
+ }
+
+ public void skipWhiteSpace()
+ {
+ while (Character.isWhitespace(buf[idx]))
+ { idx++;
+ }
+ }
+
+ private int skipWhiteSpace(int k)
+ {
+ while (Character.isWhitespace(buf[k]))
+ { k++;
+ }
+ return k;
+ }
+
+ public boolean atEnd()
+ {
+ return idx == len;
+ }
+
+ public boolean atBeginning()
+ {
+ return idx == 0;
+ }
+
+ public void ungetc()
+ {
+ if (idx > 0)
+ { idx--;
+ }
+ }
+
+ public char getc()
+ {
+ char c = buf[idx];
+ if (idx < len)
+ { idx++;
+ }
+ return c;
+ }
+
+ public char peekc()
+ {
+ return buf[idx];
+ }
+
+ public String substring (int i0, int i1)
+ {
+ if (i0 < 0)
+ { i0 = 0;
+ }
+ else if (i0 >= len)
+ { i0= len-1;
+ }
+ if (i1 < 0)
+ { i1 = 0;
+ }
+ else if (i1 > len)
+ { i1= len;
+ }
+ if (i1 <= i0)
+ { return "";
+ }
+ return new String (buf, i0, i1-i0);
+ }
+
+ public String substring (int i0)
+ {
+ if (i0 < 0)
+ { i0 = 0;
+ }
+ if (i0 >= len)
+ { return "";
+ }
+ else
+ { return new String (buf, i0, len-i0);
+ }
+ }
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java b/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
index 028df6c1..a16a6cc5 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -27,45 +26,38 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
+
+
/**
- * CMS Test Framework. Use this class to Configure a CA, RA,DRM,OCSP and SubCA
- * subsystem. This simulartes the installation wizard functions and helps to
- * configure a CMS subsystem.
+ * CMS Test Framework.
+ * Use this class to Configure a CA, RA,DRM,OCSP and SubCA subsystem.
+ * This simulartes the installation wizard functions and helps to configure a CMS subsystem.
*/
+
public class AutoInstaller {
private static Properties props = null;
- // Admin Server and InternalDB varialbes
- private String adminDomain, adminID, adminPWD, adminPort, machineName,
- host, serverID, instanceID, serverRoot, sieURL, dbConnPort,
- dbConnHost, dbInstanceName, dbPassword, dbLDAPauthDN, dbmode,
- ldapServerDB;
+ // Admin Server and InternalDB varialbes
+ private String adminDomain, adminID, adminPWD, adminPort, machineName, host, serverID, instanceID, serverRoot, sieURL, dbConnPort, dbConnHost, dbInstanceName, dbPassword, dbLDAPauthDN, dbmode, ldapServerDB;
// CMS Subsystem info
- private String certAdminName, certAdminUid, certAdminPWD, kra, subsystems,
- ca, ra, ocsp, remoteKRA, wirelessSupport, eeHttpPort, eeHttpsPort,
- agentHttpsPort, radminHttpsPort, tokenName, tokenPWD, certType,
- keyType, keyLength, SingleSignOnPWD, subjectName, aki, isCA, ski,
- sslCABit, objectSigningCABit, mailCABit, hashType, caOComponent,
- certValidityDays, signingCert, tks;
+ private String certAdminName, certAdminUid, certAdminPWD, kra, subsystems, ca, ra, ocsp, remoteKRA, wirelessSupport, eeHttpPort, eeHttpsPort, agentHttpsPort, radminHttpsPort, tokenName, tokenPWD, certType, keyType, keyLength, SingleSignOnPWD, subjectName, aki, isCA, ski, sslCABit, objectSigningCABit, mailCABit, hashType, caOComponent, certValidityDays, signingCert, tks;
// CA info
- private String caHostname, caPortnum, caTimeout, caEEPort, enpropfile,
- cdir, tokenpwd, CAadminId, CAadminPwd, CAcertnickname,
- caAgentPortnum, cloneInstanceId;
+ private String caHostname, caPortnum, caTimeout, caEEPort, enpropfile, cdir, tokenpwd, CAadminId, CAadminPwd, CAcertnickname, caAgentPortnum, cloneInstanceId;
- // Program variables
+ // Program variables
private int i;
private String configURL, deamonURL, certInstID;
private String inputLine;
private boolean st = false;
-
+
private String postQuery = null;
private String propFileName;
- private StringBuffer spage = new StringBuffer();
+ private StringBuffer spage = new StringBuffer();
// 4.5 server String CERTtokenName="Internal Key Storage Token";
private String CERTtokenName = "internal";
@@ -76,10 +68,9 @@ public class AutoInstaller {
private boolean subca = false;
- // / Constructors
+ // / Constructors
- public AutoInstaller() {
- }
+ public AutoInstaller() {}
/**
* Constructor . Takes parameter Server Root .
@@ -90,13 +81,10 @@ public class AutoInstaller {
// Set InternalDBVInfo
/**
- * Set Internal Database Information . Takes parameters internaldatabase
- * hostname, internaldatabase port, internaldatabase name, internaldatabase
- * binddn, internaldatabase password
+ * Set Internal Database Information . Takes parameters internaldatabase hostname, internaldatabase port, internaldatabase name, internaldatabase binddn, internaldatabase password
*/
- public void setInternalDBInfo(String dbh, String dbp, String dbname,
- String dbdn, String dbpswd) {
+ public void setInternalDBInfo(String dbh, String dbp, String dbname, String dbdn, String dbpswd) {
dbConnPort = dbp;
dbConnHost = dbh;
dbInstanceName = dbname;
@@ -106,14 +94,14 @@ public class AutoInstaller {
ldapServerDB = "userRoot";
}
- // Create Password file
+ // Create Password file
private boolean CreatePasswordFile() {
String s = "internal: " + SingleSignOnPWD;
OutputStream f0 = null;
try {
- f0 = new FileOutputStream(serverRoot + "/" + instanceID
- + "/config/password.conf");
+ f0 = new FileOutputStream(
+ serverRoot + "/" + instanceID + "/config/password.conf");
f0.write(s.getBytes());
f0.close();
@@ -121,8 +109,7 @@ public class AutoInstaller {
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
try {
- if (f0 != null)
- f0.close();
+ if (f0 != null) f0.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
@@ -135,8 +122,8 @@ public class AutoInstaller {
FileInputStream f1 = null;
OutputStream f2 = null;
try {
- f1 = new FileInputStream(serverRoot + "/" + instanceID
- + "/config/CS.cfg");
+ f1 = new FileInputStream(
+ serverRoot + "/" + instanceID + "/config/CS.cfg");
int size = f1.available();
byte b[] = new byte[size];
@@ -144,34 +131,32 @@ public class AutoInstaller {
f1.close();
return false;
}
- f2 = new FileOutputStream(serverRoot + "/" + instanceID
- + "/config/CS.cfg.org");
+ f2 = new FileOutputStream(
+ serverRoot + "/" + instanceID + "/config/CS.cfg.org");
f2.write(b);
f1.close();
- f2.close();
+ f2.close();
return true;
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
try {
- if (f1 != null)
- f1.close();
+ if (f1 != null) f1.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
try {
- if (f2 != null)
- f2.close();
+ if (f2 != null) f2.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
return false;
}
-
+
}
- // Get RaSigning Cert
+ // Get RaSigning Cert
public String getRASigningCert() {
return raSigningCert;
@@ -185,11 +170,9 @@ public class AutoInstaller {
// Set Admin Server Info
/**
- * Set Admin Server Information . Takes parameters : hostname, adminserver
- * portnumber , adminId , adminPassword
+ * Set Admin Server Information . Takes parameters : hostname, adminserver portnumber , adminId , adminPassword
*/
- public void setAdminInfo(String h, String p, String adDN, String id,
- String adpwd) {
+ public void setAdminInfo(String h, String p, String adDN, String id, String adpwd) {
adminDomain = adDN;
adminID = id;
adminPWD = adpwd;
@@ -198,14 +181,12 @@ public class AutoInstaller {
}
- // Set CA Server Info
+ // Set CA Server Info
/**
- * Set CA server Information . Takes parametrers :CAhostname, CAEEPORT,
- * CAAGENTPORT , CAAdminUID, CAAdminPassword
+ * Set CA server Information . Takes parametrers :CAhostname, CAEEPORT, CAAGENTPORT , CAAdminUID, CAAdminPassword
*/
- public void setCAInfo(String cah, String caeep, String caagp,
- String caaduid, String caadpwd) {
+ public void setCAInfo(String cah, String caeep, String caagp, String caaduid, String caadpwd) {
caHostname = cah;
caPortnum = caagp;
caTimeout = "30";
@@ -218,9 +199,8 @@ public class AutoInstaller {
// Set ClientDB Info;
/**
- * Sets Client Database information . Takes paramters : certdbdir,
- * certdbpasswd, certnickanme
- */
+ * Sets Client Database information . Takes paramters : certdbdir, certdbpasswd, certnickanme
+ */
public void setClientDBInfo(String cd, String pwd, String nickname) {
@@ -240,19 +220,13 @@ public class AutoInstaller {
}
- // Set Subsystem Information for Configuring
+ // Set Subsystem Information for Configuring
/**
- * Takes parameters - sID- ServerID e.x cert1, sRoot- ServerRootK kT-
- * keyType "RSA/DSA" , kL - keylength (1024.2048) , cVD- certificate
- * validity dates e.g 365 for 1 year, sdn - subsystems dn, sAdp -
- * subsystem's Admin port, sAgp - subsystems's Agentport,seSP- subsystem's
- * ee SSL port , sep- Subsystems ee port.
+ * Takes parameters - sID- ServerID e.x cert1, sRoot- ServerRootK kT- keyType "RSA/DSA" , kL - keylength (1024.2048) , cVD- certificate validity dates e.g 365 for 1 year, sdn - subsystems dn, sAdp - subsystem's Admin port, sAgp - subsystems's Agentport,seSP- subsystem's ee SSL port , sep- Subsystems ee port.
*/
- public void setSubSystemInfo(String sID, String sRoot, String kT,
- String kL, String hT, String cVD, String sdn, String sAdP,
- String sAgP, String seSP, String seP) {
+ public void setSubSystemInfo(String sID, String sRoot, String kT, String kL, String hT, String cVD, String sdn, String sAdP, String sAgP, String seSP, String seP) {
serverID = sID;
instanceID = "cert-" + sID;
@@ -269,14 +243,12 @@ public class AutoInstaller {
caOComponent = "test";
}
- // // Configure CMS Subsystems
+ // // Configure CMS Subsystems
/**
- * Confiures a CA Subsystem .Takes parameter : adminSubjectDN, adminUID,
- * AdminPasswd, SingleSignonPasswd
+ * Confiures a CA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
- public boolean ConfigureCA(String adn, String aduid, String adp,
- String ssonpwd) {
+ public boolean ConfigureCA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
@@ -308,14 +280,13 @@ public class AutoInstaller {
}
- public boolean ConfigureTKS(String adn, String aduid, String adp,
- String ssonpwd) {
+ public boolean ConfigureTKS(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
SingleSignOnPWD = ssonpwd;
- signingCert = "raSigningCert";
+ signingCert = "raSigningCert";
certType = signingCert;
subsystems = "tks";
ra = "false";
@@ -343,13 +314,13 @@ public class AutoInstaller {
}
private boolean ConfTKS() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -363,37 +334,37 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
@@ -412,53 +383,53 @@ public class AutoInstaller {
signingCert = "server";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!certRequest(false)) {
- System.out
- .println("Configuring Cert Instance: error creating Request");
+ System.out.println(
+ "Configuring Cert Instance: error creating Request");
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -466,12 +437,11 @@ public class AutoInstaller {
}
/**
- * Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID,
- * AdminPasswd, SingleSignonPasswd
+ * Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
- public boolean ConfigureRA(String adn, String aduid, String adp,
- String ssonpwd) {
+
+ public boolean ConfigureRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
@@ -504,12 +474,11 @@ public class AutoInstaller {
}
/**
- * Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID,
- * AdminPasswd, SingleSignonPasswd
+ * Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
- public boolean ConfigureOCSP(String adn, String aduid, String adp,
- String ssonpwd) {
+
+ public boolean ConfigureOCSP(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
@@ -541,12 +510,11 @@ public class AutoInstaller {
}
/**
- * Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID,
- * AdminPasswd, SingleSignonPasswd
+ * Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
- public boolean ConfigureKRA(String adn, String aduid, String adp,
- String ssonpwd) {
+
+ public boolean ConfigureKRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
@@ -577,12 +545,11 @@ public class AutoInstaller {
}
/**
- * Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID,
- * AdminPasswd, SingleSignonPasswd
+ * Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
- public boolean ConfigureSubCA(String adn, String aduid, String adp,
- String ssonpwd) {
+
+ public boolean ConfigureSubCA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
certAdminPWD = adp;
@@ -627,8 +594,7 @@ public class AutoInstaller {
System.out.println("exception " + e.getMessage());
}
try {
- if (fis != null)
- fis.close();
+ if (fis != null) fis.close();
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.getMessage());
}
@@ -652,8 +618,8 @@ public class AutoInstaller {
}
private boolean Connect(String myStringUrl) {
- // / This functions connects to the URL and POST HTTP Request .
- // It compares with NMC_STATUS and return the status.
+ // / This functions connects to the URL and POST HTTP Request .
+ // It compares with NMC_STATUS and return the status.
System.out.println(myStringUrl);
st = false;
@@ -663,12 +629,10 @@ public class AutoInstaller {
spage = sm.getPage();
return st;
}
-
+
private boolean startDeamon() {
- // Set StringURL to connect , set the query string and Connect .Get the
- // result
- System.out
- .println("Log Info - configuring Cert Instance : Start Deamon");
+ // Set StringURL to connect , set the query string and Connect .Get the result
+ System.out.println("Log Info - configuring Cert Instance : Start Deamon");
setDeamonURL();
String myStringUrl = "http://" + host + "." + adminDomain + ":"
+ adminPort + deamonURL;
@@ -685,8 +649,8 @@ public class AutoInstaller {
private boolean configInternalDB() {
- System.out
- .println("Log Info - configuring Cert Instance : configureInternalDB");
+ System.out.println(
+ "Log Info - configuring Cert Instance : configureInternalDB");
setConfigURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
@@ -762,13 +726,13 @@ public class AutoInstaller {
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("selectSubsystems");
query += "&cmsSeed=0";
-
+
if (subsystems.equals("ca")) {
query += "&internaldb.ldapconn.host="
+ URLEncoder.encode(dbConnHost);
query += "&internaldb.ldapconn.port="
+ URLEncoder.encode(dbConnPort);
-
+
}
if (subsystems.equals("ra")) {
query += "&caHostname=" + caHostname;
@@ -801,7 +765,7 @@ public class AutoInstaller {
query += "&kra=false";
query += "&subsystems=ca";
query += "&cloning=true";
- query += "&cloningInstance=" + URLEncoder.encode(cloneInstanceId);
+ query += "&cloningInstance=" + URLEncoder.encode(cloneInstanceId);
query += "&claTimeout=" + URLEncoder.encode("60");
query += "&internaldb.ldapauth.bindDN="
+ URLEncoder.encode(dbLDAPauthDN);
@@ -1087,8 +1051,8 @@ public class AutoInstaller {
query += "&aki=true";
query += "&keyUsage=true";
query += "&caSigningCertReqFormat=PKCS10";
- }
-
+ }
+
if (subsystems.equals("ra")) {
query += "&aki=" + URLEncoder.encode(aki);
query += "&keyUsage=" + URLEncoder.encode("true");
@@ -1122,7 +1086,7 @@ public class AutoInstaller {
query += "&taskID=" + URLEncoder.encode("certRequest");
query += "&caHostname=" + caHostname;
query += "&caEEPort=" + caEEPort;
- query += "&cmsSeed=0";
+ query += "&cmsSeed=0";
setPostQueryString(query);
if (!Connect(myStringUrl)) {
@@ -1139,9 +1103,9 @@ public class AutoInstaller {
int ReqId = 0;
- UserEnroll e = new UserEnroll(caHostname, caEEPort, subjectName,
- "test", "test", null, "test", "test", cdir, tokenpwd,
- ssl_clientcert, keyLength, keyType, null, null, signingCert);
+ UserEnroll e = new UserEnroll(caHostname, caEEPort, subjectName, "test",
+ "test", null, "test", "test", cdir, tokenpwd, ssl_clientcert,
+ keyLength, keyType, null, null, signingCert);
e.setpkcs10Request(certRequestStr);
if (e.Enroll()) {
@@ -1164,8 +1128,8 @@ public class AutoInstaller {
null, null, "approve", "enrollment", "showWaiting", null, trm);
if (r.ApproveRequests(getString(ReqId)) <= -1) {
- System.out
- .println("Error : Agent request approval was not successful");
+ System.out.println(
+ "Error : Agent request approval was not successful");
return false;
}
@@ -1191,7 +1155,7 @@ public class AutoInstaller {
query += "&serverRoot=" + URLEncoder.encode(serverRoot);
query += "&caEEPort=" + caEEPort;
query += "&caHostname=" + host;
- query += "&caEEType=https";
+ query += "&caEEType=https";
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("reqSuccess");
query += "&cmsSeed=0";
@@ -1211,9 +1175,8 @@ public class AutoInstaller {
+ "-----END CERTIFICATE-----\n";
// install cert
- System.out
- .println("configuring Cert Instance : install cert :"
- + cert);
+ System.out.println(
+ "configuring Cert Instance : install cert :" + cert);
setConfigURL();
myStringUrl = "http://" + host + ":" + adminPort + configURL;
System.out.println(myStringUrl);
@@ -1225,7 +1188,7 @@ public class AutoInstaller {
if (certType.equals("raSigningCert")) {
query += "&nickname="
- + URLEncoder.encode(certType + " " + instanceID);
+ + URLEncoder.encode(certType + " " + instanceID);
raSigningCert = "-----BEGIN CERTIFICATE-----" + "\n"
+ cr.getCert() + "\n"
+ "-----END CERTIFICATE-----\n";
@@ -1238,31 +1201,30 @@ public class AutoInstaller {
kraTransportCert = cCrypto.normalize(cr.getCert());
}
- if (certType.equals("serverCert")) {
+ if (certType.equals("serverCert")) {
query += "&nickname="
- + URLEncoder.encode("Server-Cert" + " "
- + instanceID);
+ + URLEncoder.encode("Server-Cert" + " " + instanceID);
}
if (certType.equals("ocspSigningCert")) {
query += "&nickname="
+ URLEncoder.encode(certType + " " + instanceID);
}
-
+
query += "&pkcs10=" + URLEncoder.encode(cert);
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("installCert");
query += "&cmsSeed=0";
setPostQueryString(query);
- return (Connect(myStringUrl));
+ return(Connect(myStringUrl));
}
} else {
System.out.println("Error: Request is not approved");
return false;
}
- return true;
+ return true;
}
private String getString(int m) {
@@ -1274,19 +1236,19 @@ public class AutoInstaller {
private boolean createCert() {
System.out.println("configuring Cert Instance : Create Cert");
-
+
// clauclate the validity dates for the cert.
GregorianCalendar begin = new GregorianCalendar();
GregorianCalendar end = new GregorianCalendar();
Integer days = new Integer(certValidityDays);
end.add(GregorianCalendar.DATE, days.intValue());
-
+
setConfigURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
System.out.println(myStringUrl);
-
+
String query = "AdminUserPassword=" + URLEncoder.encode(adminPWD);
query += "&";
@@ -1297,39 +1259,33 @@ public class AutoInstaller {
query += "&certType=" + URLEncoder.encode(certType);
query += "&beginYear="
- + URLEncoder
- .encode(getString(begin.get(GregorianCalendar.YEAR)));
+ + URLEncoder.encode(getString(begin.get(GregorianCalendar.YEAR)));
query += "&beginMonth="
- + URLEncoder.encode(getString(begin
- .get(GregorianCalendar.MONTH)));
+ + URLEncoder.encode(
+ getString(begin.get(GregorianCalendar.MONTH)));
query += "&beginDate="
- + URLEncoder
- .encode(getString(begin.get(GregorianCalendar.DATE)));
+ + URLEncoder.encode(getString(begin.get(GregorianCalendar.DATE)));
query += "&beginHour="
- + URLEncoder
- .encode(getString(begin.get(GregorianCalendar.HOUR)));
+ + URLEncoder.encode(getString(begin.get(GregorianCalendar.HOUR)));
query += "&beginMin="
- + URLEncoder.encode(getString(begin
- .get(GregorianCalendar.MINUTE)));
+ + URLEncoder.encode(
+ getString(begin.get(GregorianCalendar.MINUTE)));
query += "&beginSec="
- + URLEncoder.encode(getString(begin
- .get(GregorianCalendar.SECOND)));
+ + URLEncoder.encode(
+ getString(begin.get(GregorianCalendar.SECOND)));
query += "&afterYear="
+ URLEncoder.encode(getString(end.get(GregorianCalendar.YEAR)));
query += "&afterMonth="
- + URLEncoder
- .encode(getString(end.get(GregorianCalendar.MONTH)));
+ + URLEncoder.encode(getString(end.get(GregorianCalendar.MONTH)));
query += "&afterDate="
+ URLEncoder.encode(getString(end.get(GregorianCalendar.DATE)));
query += "&afterHour="
+ URLEncoder.encode(getString(end.get(GregorianCalendar.HOUR)));
query += "&afterMin="
- + URLEncoder
- .encode(getString(end.get(GregorianCalendar.MINUTE)));
+ + URLEncoder.encode(getString(end.get(GregorianCalendar.MINUTE)));
query += "&afterSec="
- + URLEncoder
- .encode(getString(end.get(GregorianCalendar.SECOND)));
+ + URLEncoder.encode(getString(end.get(GregorianCalendar.SECOND)));
query += "&keyType=" + URLEncoder.encode(keyType);
query += "&keyLength=" + URLEncoder.encode(keyLength);
@@ -1342,7 +1298,7 @@ public class AutoInstaller {
if (certType.equals("serverCert")) {
query += "&sslServerBit=" + URLEncoder.encode("true");
query += "&sslClientBit=" + URLEncoder.encode("true");
-
+
} else {
query += "&caOComponent=" + URLEncoder.encode(caOComponent);
query += "&caCComponent=" + URLEncoder.encode("us");
@@ -1354,7 +1310,7 @@ public class AutoInstaller {
query += "&mailCABit=" + URLEncoder.encode(mailCABit);
query += "&objectSigningCABit="
+ URLEncoder.encode(objectSigningCABit);
-
+
}
query += "&hashType=" + URLEncoder.encode(hashType);
@@ -1388,7 +1344,7 @@ public class AutoInstaller {
query += "&pwcTokenname=" + URLEncoder.encode("internal");
query += "&singlesignon=" + URLEncoder.encode(tokenPWD);
-
+
query += "&opType=" + URLEncoder.encode("OP_MODIFY");
query += "&taskID=" + URLEncoder.encode("singleSignon");
query += "&cmsSeed=0";
@@ -1425,7 +1381,7 @@ public class AutoInstaller {
}
private boolean exitDeamon() {
-
+
System.out.println("configuring Cert Instance : Exit Deamon");
setDeamonURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
@@ -1448,8 +1404,8 @@ public class AutoInstaller {
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -1463,62 +1419,62 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
// Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
// Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
// Step 6: Initialize Token This has been moved to step 1a
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 7 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
// Step 8 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install
+ // Step 9 : certRequest and Install
if (!certRequest(false)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1539,29 +1495,29 @@ public class AutoInstaller {
signingCert = "server";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
// Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!certRequest(false)) {
- System.out
- .println("Configuring Cert Instance: error creating Request");
+ System.out.println(
+ "Configuring Cert Instance: error creating Request");
return false;
}
@@ -1570,22 +1526,22 @@ public class AutoInstaller {
// Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
// Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
// Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -1641,13 +1597,13 @@ public class AutoInstaller {
}
private boolean ConfRA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -1661,63 +1617,62 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
// Step 6: Initialize Token This has been moved to step 1a
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 7 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 8 : CheckDN
+ // Step 8 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted
- // manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted manager
if (!certRequest(true)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -1738,53 +1693,53 @@ public class AutoInstaller {
signingCert = "server";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!certRequest(false)) {
- System.out
- .println("Configuring Cert Instance: error creating Request");
+ System.out.println(
+ "Configuring Cert Instance: error creating Request");
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -1792,13 +1747,13 @@ public class AutoInstaller {
}
private boolean ConfKRA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -1812,79 +1767,77 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
// Step 6: Initialize Token This has been moved to step 1a
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 7 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 8 : CheckDN
+ // Step 8 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted
- // manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted manager
if (!certRequest(true)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
}
if (!setupStorageKey()) {
- System.out
- .println("Configuring Cert Instance: error configuring storage key");
+ System.out.println(
+ "Configuring Cert Instance: error configuring storage key");
return false;
}
// no need to do this from 7.1 due to new acl based key recovery
/*
- * if (!setupKRAAgents()) { System.out.println(
- * "Configuring Cert Instance: error configuring storage key"); return
- * false;}
+ if (!setupKRAAgents())
+ { System.out.println("Configuring Cert Instance: error configuring storage key"); return false;}
*/
// Create a SSL signing cert
@@ -1902,53 +1855,53 @@ public class AutoInstaller {
signingCert = "server";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!certRequest(false)) {
- System.out
- .println("Configuring Cert Instance: error creating Request");
+ System.out.println(
+ "Configuring Cert Instance: error creating Request");
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -1963,8 +1916,8 @@ public class AutoInstaller {
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -1978,63 +1931,62 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
// Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
// Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
// Step 6: Initialize Token This has been moved to step 1a
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 7 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
// Step 8 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
- // Step 9 : certRequest and Install i.e approve the request as a trusted
- // manager
+ // Step 9 : certRequest and Install i.e approve the request as a trusted manager
if (!certRequest(false)) {
System.out.println("Configuring Cert Instance: error getting cert");
return false;
@@ -2055,29 +2007,29 @@ public class AutoInstaller {
signingCert = "server";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
// Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!certRequest(false)) {
- System.out
- .println("Configuring Cert Instance: error creating Request");
+ System.out.println(
+ "Configuring Cert Instance: error creating Request");
return false;
}
@@ -2086,22 +2038,22 @@ public class AutoInstaller {
// Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
// Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
// Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -2112,13 +2064,13 @@ public class AutoInstaller {
// org
private boolean ConfCA() {
- // Start Configuring
+ // Start Configuring
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -2132,85 +2084,82 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
- // Step 3. Create Admin Values
+ // Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
- // Step 4. SubSystems
+ // Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
- // SetSerial Number
+ // SetSerial Number
if (!setSerial("1", "1000000")) {
- System.out
- .println("Configuring Cert Instance: error setting serial number");
+ System.out.println(
+ "Configuring Cert Instance: error setting serial number");
return false;
}
if (!setOCSP()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
- // Step 6. setting up Server Migration
+ // Step 6. setting up Server Migration
// if (!serverMigration())
- // {
- // System.out.println("Configuring Cert Instance: error configuring server migration");
- // return false;}
+ // { System.out.println("Configuring Cert Instance: error configuring server migration"); return false;}
// Step 7: Initialize Token
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!createCert()) {
- System.out
- .println("Configuring Cert Instance: error creating cert");
+ System.out.println("Configuring Cert Instance: error creating cert");
return false;
}
@@ -2227,60 +2176,59 @@ public class AutoInstaller {
tokenPWD = "";
if (!initializeToken()) {
- System.out
- .println("Configuring Cert Instance: error initializing token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing token");
return false;
}
// Step 8 : keyLenth
if (!keyLength()) {
- System.out
- .println("Configuring Cert Instance: error configuring KeyLength");
+ System.out.println(
+ "Configuring Cert Instance: error configuring KeyLength");
return false;
}
- // Step 9 : CheckDN
+ // Step 9 : CheckDN
if (!checkDN()) {
- System.out
- .println("Configuring Cert Instance: error checking deamon");
+ System.out.println(
+ "Configuring Cert Instance: error checking deamon");
return false;
}
// Step 10 :
if (!createCert()) {
- System.out
- .println("Configuring Cert Instance: error creating cert");
+ System.out.println("Configuring Cert Instance: error creating cert");
return false;
}
- // After creating ssl cert
+ // After creating ssl cert
tokenPWD = mtokenPWD;
- // Step 11
+ // Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
return true;
}
- // Configure Clone
+ // Configure Clone
private boolean ConfClone() {
// Start Configuring
@@ -2288,8 +2236,8 @@ public class AutoInstaller {
// Step 1. Start Deamon
if (!startDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to start deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to start deamon");
return false;
}
@@ -2303,30 +2251,30 @@ public class AutoInstaller {
// Step 1a: Initialize Token ( Changed in 6.0)jjj
if (!initializePWD()) {
- System.out
- .println("Configuring Cert Instance: error initializing pwd token");
+ System.out.println(
+ "Configuring Cert Instance: error initializing pwd token");
return false;
}
// Step 2. Configure Internal DB
if (!configInternalDB()) {
- System.out
- .println("Configuring Cert Instance: error configuring internal db");
+ System.out.println(
+ "Configuring Cert Instance: error configuring internal db");
return false;
}
// Step 3. Create Admin Values
if (!createAdminValues()) {
- System.out
- .println("Configuring Cert Instance: error configuring admin values ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring admin values ");
return false;
}
// Step 4. SubSystems
if (!selectSubSystem()) {
- System.out
- .println("Configuring Cert Instance: error selecting subsystems");
+ System.out.println(
+ "Configuring Cert Instance: error selecting subsystems");
return false;
}
@@ -2343,20 +2291,19 @@ public class AutoInstaller {
// Step 5. Network Configuration
if (!networkConfig()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
if (!taskCloning()) {
- System.out
- .println("Configuring Cert Instance: error Task Cloning ");
+ System.out.println("Configuring Cert Instance: error Task Cloning ");
return false;
}
if (!taskCloneMaster()) {
- System.out
- .println("Configuring Cert Instance: error configuring network ports ");
+ System.out.println(
+ "Configuring Cert Instance: error configuring network ports ");
return false;
}
@@ -2364,29 +2311,28 @@ public class AutoInstaller {
certType = "serverCert";
if (!taskCloning()) {
- System.out
- .println("Configuring Cert Instance: error Task Cloning ");
+ System.out.println("Configuring Cert Instance: error Task Cloning ");
return false;
}
- // Step 11
+ // Step 11
if (!singleSignON()) {
- System.out
- .println("Configuring Cert Instance: error setting up singlesignon");
+ System.out.println(
+ "Configuring Cert Instance: error setting up singlesignon");
return false;
}
- // Step 11
+ // Step 11
if (!doMisc()) {
- System.out
- .println("Configuring Cert Instance: error setting up miscell");
+ System.out.println(
+ "Configuring Cert Instance: error setting up miscell");
return false;
}
- // Step 12
+ // Step 12
if (!exitDeamon()) {
- System.out
- .println("Configuring Cert Instance: Unable to exit deamon");
+ System.out.println(
+ "Configuring Cert Instance: Unable to exit deamon");
return false;
}
@@ -2399,11 +2345,11 @@ public class AutoInstaller {
try {
getProperties(propFileName);
} catch (Exception e) {
- System.out.println("exception reading Properties File "
- + e.getMessage());
+ System.out.println(
+ "exception reading Properties File " + e.getMessage());
}
- // read all properties
+ // read all properties
adminDomain = props.getProperty("inst.admin.domain");
adminID = props.getProperty("inst.admin.uid");
@@ -2475,12 +2421,12 @@ public class AutoInstaller {
}
if (subsystems.equals("ocsp")) {
return ConfOCSP();
- }
+ }
if (subsystems.equals("kra")) {
return ConfKRA();
}
if (subsystems.equals("subca")) {
- subca = true;
+ subca = true;
subsystems = "ca";
return ConfSubCA();
}
@@ -2490,8 +2436,9 @@ public class AutoInstaller {
public static void main(String args[]) {
// Exit Status - (-1) for error
- // - 1 Configured and server Alive
- // - 0 Configured bur could not sart server
+ // - 1 Configured and server Alive
+ // - 0 Configured bur could not sart server
+
AutoInstaller t = new AutoInstaller();
@@ -2501,13 +2448,13 @@ public class AutoInstaller {
if (args.length < 1) {
System.out.println("Usage : PropertiesFilePath");
System.exit(-1);
- }
-
+ }
+
System.out.println("configuring Cert Instance : Start");
boolean st = t.readProperties();
- if (st) {
+ if (st) {
System.out.println("Configuring Cert Instance : Successful");
System.exit(1);
} else {
@@ -2517,5 +2464,5 @@ public class AutoInstaller {
}
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java b/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
index b9740ee4..a3ceec31 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,41 +17,42 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
+
/**
- * CMS Test framework . This class reads and sets the values for a CMS subsytems
- * Config file (CS.cfg) Using this class you can set the server to a base state.
+ * CMS Test framework .
+ * This class reads and sets the values for a CMS subsytems Config file (CS.cfg)
+ * Using this class you can set the server to a base state.
*/
+
+
public class BaseState {
private String CMSConfigFile;
private CMSConfig cmscfg = null;
private String ldapbase, ldaphost, ldapport, ldapdn, ldapdnpw;
private boolean ldapsecConn = false;
+ // Constructor
- // Constructor
- public BaseState() {
- }
+
+ public BaseState() {}
/**
- * Constructor . Takes the parameter CMSConfigfilename ( with fullpath)
- *
+ * Constructor . Takes the parameter CMSConfigfilename ( with fullpath)
* @param CMSConfigfile.
*/
- public BaseState(String cmscfilename) {
+ public BaseState(String cmscfilename) {
CMSConfigFile = cmscfilename;
}
/**
- * Set the publishing directory information . Takes the paramters
- * ldaphost,ldapport,ldapDN, ldapDN password, BaseDN , Secure coonection
- * (true/false)
+ * Set the publishing directory information . Takes the paramters ldaphost,ldapport,ldapDN, ldapDN password, BaseDN , Secure coonection (true/false)
*/
- public void setLDAPInfo(String h, String p, String dn, String pw,
- String base, boolean sc) {
+ public void setLDAPInfo(String h, String p, String dn, String pw, String base, boolean sc) {
ldaphost = h;
ldapport = p;
ldapdn = dn;
@@ -63,8 +63,8 @@ public class BaseState {
}
/**
- * Enable SSL Client authentication for Directory enrollment and publishing
- */
+ * Enable SSL Client authentication for Directory enrollment and publishing
+ */
public void EnableSSLClientAuth() {
ldapsecConn = true;
@@ -79,8 +79,7 @@ public class BaseState {
}
/**
- * Set to CA 's base state . Enables Directory based enrollment , publishing
- * and Portal enrollment
+ * Set to CA 's base state . Enables Directory based enrollment , publishing and Portal enrollment
*/
public void CABaseState() {
@@ -99,10 +98,10 @@ public class BaseState {
}
/**
- * Set to RA 's base state . Enables Directory based enrollment and Portal
- * enrollment
+ * Set to RA 's base state . Enables Directory based enrollment and Portal enrollment
*/
+
public void RABaseState() {
cmscfg = new CMSConfig(CMSConfigFile);
cmscfg.EnableAdminEnrollment();
@@ -115,7 +114,6 @@ public class BaseState {
}
- public static void main(String args[]) {
- }// end of function main
+ public static void main(String args[]) {}// end of function main
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
index 88d9ac84..6913a144 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -21,17 +20,20 @@ package com.netscape.pkisilent.common;
import java.io.FileInputStream;
import java.io.FileOutputStream;
+
/**
- * CMS Test framework . This class reads,modifies and saves CS.cfg file
+ * CMS Test framework .
+ * This class reads,modifies and saves CS.cfg file
*/
-public class CMSConfig extends ServerInfo {
+
+public class CMSConfig extends ServerInfo {
/**
- * Constructor . Reads the CS.cfg file .Takes the parameter for Configfile (
- * Provide fullpath)
+ * Constructor . Reads the CS.cfg file .Takes the parameter for Configfile ( Provide fullpath)
*/
+
public CMSConfig(String confFile) {
CMSConfigFile = confFile;
System.out.println(CMSConfigFile);
@@ -69,7 +71,7 @@ public class CMSConfig extends ServerInfo {
}
/**
- * Saves the config file
+ * Saves the config file
**/
public void saveCMSConfig() {
@@ -95,16 +97,15 @@ public class CMSConfig extends ServerInfo {
}
- // Authentication
+ // Authentication
+
// Enable DirectoryBased Authentication
/**
- * Takes parameters : secureConnection( true/false), basedn, ldaphostname,
- * lapdaportnumber ( in case of secured connection give ldap secured port)
+ * Takes parameters : secureConnection( true/false), basedn, ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port)
*/
- public void EnableDirEnrollment(boolean secureConn, String ldapbase,
- String lhost, String lport) {
+ public void EnableDirEnrollment(boolean secureConn, String ldapbase, String lhost, String lport) {
CMSprops.setProperty("auths.instance.UserDirEnrollment.dnpattern",
"UID=$attr.uid,E=$attr.mail.1,CN=$attr.cn,OU=$dn.ou.2,O=$dn.o,C=US");
CMSprops.setProperty("auths.instance.UserDirEnrollment.ldap.basedn",
@@ -127,16 +128,14 @@ public class CMSConfig extends ServerInfo {
"auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn",
"true");
CMSprops.setProperty(
- "auths.instance.UserDirEnrollment.ldap.ldapconn.port",
- lport);
+ "auths.instance.UserDirEnrollment.ldap.ldapconn.port", lport);
} else {
CMSprops.setProperty(
"auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn",
"false");
CMSprops.setProperty(
- "auths.instance.UserDirEnrollment.ldap.ldapconn.port",
- lport);
+ "auths.instance.UserDirEnrollment.ldap.ldapconn.port", lport);
}
}
@@ -146,7 +145,8 @@ public class CMSConfig extends ServerInfo {
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.basedn");
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.host");
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.port");
- CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn");
+ CMSprops.remove(
+ "auths.instance.UserDirEnrollment.ldap.ldapconn.secureConn");
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.ldapconn.version");
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.maxConns");
CMSprops.remove("auths.instance.UserDirEnrollment.ldap.minConns");
@@ -163,13 +163,10 @@ public class CMSConfig extends ServerInfo {
}
/**
- * Takes parameters : secureConnection( true/false), ldapbinddn,
- * ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured
- * connection give ldap secured port), basedn (e.g ou=people,o=mcom.com)
+ * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port), basedn (e.g ou=people,o=mcom.com)
*/
- void EnablePortalAuth(boolean secureConn, String ldaprootDN,
- String ldaprootDNPW, String lhost, String lport, String lbsuffix) {
+ void EnablePortalAuth(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport, String lbsuffix) {
String certnickname = null;
CMSprops.setProperty("auths.instance.PortalEnrollment.pluginName",
@@ -182,8 +179,7 @@ public class CMSConfig extends ServerInfo {
"3");
CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.minConns",
"2");
- CMSprops.setProperty(
- "auths.instance.PortalEnrollment.ldap.objectclass",
+ CMSprops.setProperty("auths.instance.PortalEnrollment.ldap.objectclass",
"inetOrgPerson");
CMSprops.setProperty(
"auths.instance.PortalEnrollment.ldap.ldapauth.bindDN",
@@ -225,15 +221,12 @@ public class CMSConfig extends ServerInfo {
}
- // Publishing
+ // Publishing
/**
- * Takes parameters : secureConnection( true/false), ldapbinddn,
- * ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured
- * connection give ldap secured port)
+ * Takes parameters : secureConnection( true/false), ldapbinddn, ldapbindnpassword,ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port)
*/
- public void EnablePublishing(boolean secureConn, String ldaprootDN,
- String ldaprootDNPW, String lhost, String lport) {
+ public void EnablePublishing(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport) {
CMSprops.setProperty("ca.publish.enable", "true");
CMSprops.setProperty("ca.publish.ldappublish.enable", "true");
@@ -243,32 +236,27 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port",
lport);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.authtype",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype",
"SslClientAuth");
} else {
CMSprops.setProperty(
"ca.publish.ldappublish.ldap.ldapconn.secureConn", "false");
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port",
lport);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.authtype",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype",
"BasicAuth");
}
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindDN",
ldaprootDN);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.bindPassword",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPassword",
ldaprootDNPW);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
"CA LDAP Publishing");
// set the hostname with fully qulified name if you are using SSL
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.host", lhost);
- CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version",
- "3");
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version", "3");
CMSprops.setProperty("ca.publish.mapper.impl.LdapCaSimpleMap.class",
"com.netscape.cms.publish.mappers.LdapCaSimpleMap");
CMSprops.setProperty("ca.publish.mapper.impl.LdapDNCompsMap.class",
@@ -282,8 +270,7 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty("ca.publish.mapper.impl.LdapSubjAttrMap.class",
"com.netscape.cms.publish.mappers.LdapCertSubjMap");
CMSprops.setProperty(
- "ca.publish.mapper.instance.LdapCaCertMap.createCAEntry",
- "true");
+ "ca.publish.mapper.instance.LdapCaCertMap.createCAEntry", "true");
CMSprops.setProperty(
"ca.publish.mapper.instance.LdapCaCertMap.dnPattern",
"UID=CManager,OU=people,O=mcom.com");
@@ -294,8 +281,7 @@ public class CMSConfig extends ServerInfo {
"ca.publish.mapper.instance.LdapCrlMap.createCAEntry", "true");
CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.dnPattern",
"UID=CManager,OU=people,O=mcom.com");
- CMSprops.setProperty(
- "ca.publish.mapper.instance.LdapCrlMap.pluginName",
+ CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.pluginName",
"LdapCaSimpleMap");
CMSprops.setProperty(
"ca.publish.mapper.instance.LdapUserCertMap.dnPattern",
@@ -309,8 +295,7 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty(
"ca.publish.publisher.impl.LdapCaCertPublisher.class",
"com.netscape.cms.publish.publishers.LdapCaCertPublisher");
- CMSprops.setProperty(
- "ca.publish.publisher.impl.LdapCrlPublisher.class",
+ CMSprops.setProperty("ca.publish.publisher.impl.LdapCrlPublisher.class",
"com.netscape.cms.publish.publishers.LdapCrlPublisher");
CMSprops.setProperty(
"ca.publish.publisher.impl.LdapUserCertPublisher.class",
@@ -340,8 +325,7 @@ public class CMSConfig extends ServerInfo {
"LdapUserCertPublisher");
}
- public void DisablePublishing(boolean secureConn, String ldaprootDN,
- String ldaprootDNPW, String lhost, String lport, String base) {
+ public void DisablePublishing(boolean secureConn, String ldaprootDN, String ldaprootDNPW, String lhost, String lport, String base) {
CMSprops.setProperty("ca.publish.enable", "false");
CMSprops.setProperty("ca.publish.ldappublish.enable", "false");
@@ -351,32 +335,27 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port",
lport);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.authtype",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype",
"SslClientAuth");
} else {
CMSprops.setProperty(
"ca.publish.ldappublish.ldap.ldapconn.secureConn", "false");
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.port",
lport);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.authtype",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.authtype",
"BasicAuth");
}
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindDN",
ldaprootDN);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.bindPassword",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPassword",
ldaprootDNPW);
- CMSprops.setProperty(
- "ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapauth.bindPWPrompt",
"CA LDAP Publishing");
// set the hostname with fully qulified name if you are using SSL
CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.host", lhost);
- CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version",
- "3");
+ CMSprops.setProperty("ca.publish.ldappublish.ldap.ldapconn.version", "3");
CMSprops.setProperty("ca.publish.mapper.impl.LdapCaSimpleMap.class",
"com.netscape.cms.publish.mappers.LdapCaSimpleMap");
CMSprops.setProperty("ca.publish.mapper.impl.LdapDNCompsMap.class",
@@ -402,8 +381,7 @@ public class CMSConfig extends ServerInfo {
"ca.publish.mapper.instance.LdapCrlMap.createCAEntry", "false");
CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.dnPattern",
"UID=CManager,OU=people," + base);
- CMSprops.setProperty(
- "ca.publish.mapper.instance.LdapCrlMap.pluginName",
+ CMSprops.setProperty("ca.publish.mapper.instance.LdapCrlMap.pluginName",
"LdapCaSimpleMap");
CMSprops.setProperty(
"ca.publish.mapper.instance.LdapUserCertMap.dnPattern",
@@ -417,8 +395,7 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty(
"ca.publish.publisher.impl.LdapCaCertPublisher.class",
"com.netscape.cms.publish.publishers.LdapCaCertPublisher");
- CMSprops.setProperty(
- "ca.publish.publisher.impl.LdapCrlPublisher.class",
+ CMSprops.setProperty("ca.publish.publisher.impl.LdapCrlPublisher.class",
"com.netscape.cms.publish.publishers.LdapCrlPublisher");
CMSprops.setProperty(
"ca.publish.publisher.impl.LdapUserCertPublisher.class",
@@ -448,9 +425,8 @@ public class CMSConfig extends ServerInfo {
"LdapUserCertPublisher");
}
- public void CreateOCSPPublisher(String OCSPHost, String OCSPPort,
- String OCSPEEPort) {
- // Set host nmae with fully qualified hostname
+ public void CreateOCSPPublisher(String OCSPHost, String OCSPPort, String OCSPEEPort) {
+ // Set host nmae with fully qualified hostname
String location = "http://" + OCSPHost + ":" + OCSPEEPort + "/ocsp";
CMSprops.setProperty("ca.crl.MasterCRL.alwaysUpdate", "true");
@@ -469,15 +445,14 @@ public class CMSConfig extends ServerInfo {
CMSprops.setProperty(
"ca.publish.rule.instance.OCSPPublishingRule.mapper", "");
CMSprops.setProperty(
- "ca.publish.rule.instance.OCSPPublishingRule.pluginName",
- "Rule");
+ "ca.publish.rule.instance.OCSPPublishingRule.pluginName", "Rule");
CMSprops.setProperty(
"ca.publish.rule.instance.OCSPPublishingRule.predicate", "");
CMSprops.setProperty(
"ca.publish.rule.instance.OCSPPublishingRule.publisher",
"CAOCSPPublisher");
- CMSprops.setProperty(
- "ca.publish.rule.instance.OCSPPublishingRule.type", "crl");
+ CMSprops.setProperty("ca.publish.rule.instance.OCSPPublishingRule.type",
+ "crl");
CMSprops.setProperty("ca.Policy.rule.AuthInfoAccessExt.ad0_location",
location);
CMSprops.setProperty(
@@ -525,8 +500,7 @@ public class CMSConfig extends ServerInfo {
}
- public void SetupKRAConnectorInCA(String certInstanceID, String KRAHost,
- String KRAPort) {
+ public void SetupKRAConnectorInCA(String certInstanceID, String KRAHost, String KRAPort) {
String certNickName = "Server-Cert " + certInstanceID;
CMSprops.setProperty("ca.connector.KRA.enable", "true");
@@ -588,9 +562,8 @@ public class CMSConfig extends ServerInfo {
}
- // Policies
- public void DefaultValidityRule(String SubsystemType, String lagtime,
- String leadtime, String maxValidity) {
+ // Policies
+ public void DefaultValidityRule(String SubsystemType, String lagtime, String leadtime, String maxValidity) {
if (SubsystemType.equals("ca")) {
CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.enable",
"true");
@@ -607,8 +580,8 @@ public class CMSConfig extends ServerInfo {
"ca.Policy.rule.DefaultValidityRule.minValidity", "1");
CMSprops.setProperty(
"ca.Policy.rule.DefaultValidityRule.notBeforeSkew", "5");
- CMSprops.setProperty(
- "ca.Policy.rule.DefaultValidityRule.predicate", null);
+ CMSprops.setProperty("ca.Policy.rule.DefaultValidityRule.predicate",
+ null);
} else {
CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.enable",
@@ -626,8 +599,8 @@ public class CMSConfig extends ServerInfo {
"ra.Policy.rule.DefaultValidityRule.minValidity", "1");
CMSprops.setProperty(
"ra.Policy.rule.DefaultValidityRule.notBeforeSkew", "5");
- CMSprops.setProperty(
- "ra.Policy.rule.DefaultValidityRule.predicate", null);
+ CMSprops.setProperty("ra.Policy.rule.DefaultValidityRule.predicate",
+ null);
}
}
@@ -644,10 +617,10 @@ public class CMSConfig extends ServerInfo {
CMSConfig s = new CMSConfig(args[0]);
boolean secureC = false;
- // s.EnableDirEnrollment(secureC);
+ // s.EnableDirEnrollment(secureC);
s.saveCMSConfig();
-
+
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
index 75e7e438..0687bc2a 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -26,34 +25,26 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
+
public class CMSInstance {
private int i;
private boolean st;
- private String host, port, AdminDN, AdminDNPW, serverRoot, instanceID,
- sieurl, adminDomain, machineName;
+ private String host, port, AdminDN, AdminDNPW, serverRoot, instanceID, sieurl, adminDomain, machineName;
/**
- * CMS Test framework . This class Creates and Removes a CMS server instance
+ * CMS Test framework .
+ * This class Creates and Removes a CMS server instance
*/
+
/**
- * Constructor. Takes parameters hostname, adminserverport, adminDN,
- * adminDNpassword, Dominanname, ServerRoot( full path) , instanceID,
- * mnameand sieURL. mname is the fully qualified name of the server (
- * jupiter2.nscp.aoltw.net) sieURL is
- * ("ldap://jupiter2.nscp.aoltw.net:(ConfigLADPPort)/o=NetscapeRoot"
+ * Constructor. Takes parameters hostname, adminserverport, adminDN, adminDNpassword, Dominanname, ServerRoot( full path) , instanceID, mnameand sieURL. mname is the fully qualified name of the server ( jupiter2.nscp.aoltw.net) sieURL is ("ldap://jupiter2.nscp.aoltw.net:(ConfigLADPPort)/o=NetscapeRoot"
*/
- private String cs_server_root, cs_tps_root, tps_hostname, tps_fqdn,
- tps_instanceid, tps_ee_port, tps_agent_port, tps_auth_ldap_host,
- tps_auth_ldap_port, tps_auth_ldap_suffix, ca_hostname, ca_ee_port,
- tks_hostname, tks_agent_port, token_db_hostname, token_db_port,
- token_db_suffix, token_db_passwd;
+ private String cs_server_root, cs_tps_root, tps_hostname, tps_fqdn, tps_instanceid, tps_ee_port, tps_agent_port, tps_auth_ldap_host, tps_auth_ldap_port, tps_auth_ldap_suffix, ca_hostname, ca_ee_port, tks_hostname, tks_agent_port, token_db_hostname, token_db_port, token_db_suffix, token_db_passwd;
- public CMSInstance(String h, String p, String AdDN, String pwd,
- String domain, String sroot, String insID, String mname,
- String sieURL) {
+ public CMSInstance(String h, String p, String AdDN, String pwd, String domain, String sroot, String insID, String mname, String sieURL) {
host = h;
port = p;
@@ -66,11 +57,24 @@ public class CMSInstance {
sieurl = sieURL;
}
- public CMSInstance(String croot, String troot, String th, String tfqdn,
- String tid, String tep, String tagp, String tldaphost,
- String tldapport, String tldapsuffix, String ch, String ceep,
- String tkh, String tkagp, String toh, String toagp,
- String tosuffix, String topasswd) {
+ public CMSInstance(String croot,
+ String troot,
+ String th,
+ String tfqdn,
+ String tid,
+ String tep,
+ String tagp,
+ String tldaphost,
+ String tldapport,
+ String tldapsuffix,
+ String ch,
+ String ceep,
+ String tkh,
+ String tkagp,
+ String toh,
+ String toagp,
+ String tosuffix,
+ String topasswd) {
cs_server_root = croot;
cs_tps_root = troot;
@@ -97,9 +101,9 @@ public class CMSInstance {
// steps
// 1. create .cfg file
// 2. run create.pl with that .cfg file
-
- FileOutputStream out = new FileOutputStream(cs_server_root
- + "/tps_auto_config.cfg");
+
+ FileOutputStream out = new FileOutputStream(
+ cs_server_root + "/tps_auto_config.cfg");
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
@@ -146,28 +150,27 @@ public class CMSInstance {
try {
Process p = null;
Runtime r = Runtime.getRuntime();
- // String[] se = {"perl",
- // cs_server_root+"/bin/cert/tps/setup/create.pl" , "-i",
- // cs_server_root+"/tps_auto_config.cfg" };
- String[] se = { "perl",
- "/home/ckannan/cms/src/ns/netkeyra/setup/create.pl", "-i",
- cs_server_root + "/tps_auto_config.cfg" };
+ // String[] se = {"perl", cs_server_root+"/bin/cert/tps/setup/create.pl" , "-i", cs_server_root+"/tps_auto_config.cfg" };
+ String[] se = {
+ "perl",
+ "/home/ckannan/cms/src/ns/netkeyra/setup/create.pl", "-i",
+ cs_server_root + "/tps_auto_config.cfg" };
System.out.println(se);
- p = r.exec(se);
+ p = r.exec(se);
p.waitFor();
String line;
if (p.exitValue() == 0) {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(p.getInputStream()));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} else {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getErrorStream()));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(p.getErrorStream()));
while ((line = br.readLine()) != null) {
System.out.println(line);
@@ -189,7 +192,7 @@ public class CMSInstance {
+ startURL;
System.out.println(myStringUrl);
-
+
String query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&instanceID=" + URLEncoder.encode(instanceID);
@@ -202,7 +205,7 @@ public class CMSInstance {
PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
return (sm.Send());
-
+
}
public boolean RemoveInstance() {
@@ -211,11 +214,11 @@ public class CMSInstance {
String myStringUrl = "http://" + host + ":" + port + startURL;
System.out.println(myStringUrl);
-
+
String query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&instanceID=" + URLEncoder.encode(instanceID);
-
+
PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
st = sm.Send();
@@ -230,15 +233,15 @@ public class CMSInstance {
myStringUrl = "http://" + host + ":" + port + startURL;
System.out.println(myStringUrl);
-
+
query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&InstanceName=" + URLEncoder.encode(instanceID + "-db");
-
+
PostQuery rmdb = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
rmdb.setNMCStatus("NMC_Status: 0");
return (rmdb.Send());
-
+
}
public static void main(String args[]) {
@@ -247,51 +250,50 @@ public class CMSInstance {
// Exit Status - (-1) for error
// - 0 FAIL
// - 1 PASS
-
+
boolean st;
-
+
System.out.println(args.length);
if (args.length < 10) {
- System.out
- .println("Usage : <task:Create/REmove> host port AdminDN AdminDNPW adminDomain serverRoot instanceID machineName sieURL");
+ System.out.println(
+ "Usage : <task:Create/REmove> host port AdminDN AdminDNPW adminDomain serverRoot instanceID machineName sieURL");
System.exit(-1);
- }
+ }
int task = 0;
args[0] = args[0].toLowerCase();
- if (args[0].equals("create")) {
+ if (args[0].equals("create")) {
task = 0;
}
if (args[0].equals("remove")) {
task = 1;
}
-
+
CMSInstance t = new CMSInstance(args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8], args[9]);
switch (task) {
-
+
case 0:
st = t.CreateInstance();
- if (st) {
+ if (st) {
System.out.println("server Instance created ");
System.exit(1);
} else {
-
- System.out
- .println("Error: Server Instance could not be created");
+
+ System.out.println("Error: Server Instance could not be created");
System.exit(0);
}
break;
case 1:
st = t.RemoveInstance();
- if (st) {
+ if (st) {
System.out.println("Server instance removed");
System.exit(1);
} else {
-
+
System.out.println("Server instance could not be removed");
System.exit(0);
}
@@ -304,5 +306,5 @@ public class CMSInstance {
} // end of switch
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
index 62d8b185..51dbd212 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -32,12 +31,15 @@ import netscape.ldap.LDAPModificationSet;
import netscape.ldap.LDAPSearchResults;
import netscape.ldap.LDAPv2;
+
/**
- * CMS Test framework . Using this class you can add a user and user certificate
- * to LDAP server. You can also check if a certificate / CRL is published in
- * LDAP server USe this class to turn of SSL and turn on SSL in a LDAP server.
+ * CMS Test framework .
+ * Using this class you can add a user and user certificate to LDAP server.
+ * You can also check if a certificate / CRL is published in LDAP server
+ * USe this class to turn of SSL and turn on SSL in a LDAP server.
*/
+
public class CMSLDAP {
private String HOST, DN, BASEDN, PASSWORD;
@@ -45,8 +47,7 @@ public class CMSLDAP {
private LDAPConnection conn = new LDAPConnection();
- public CMSLDAP() {
- }
+ public CMSLDAP() {}
/**
* Constructor. Takes parametes ldaphost, ldapport
@@ -57,8 +58,7 @@ public class CMSLDAP {
}
/**
- * Cosntructor. Takes parameters ldaphost,ldapport,ldapbinddn,
- * ldapbindnpassword.
+ * Cosntructor. Takes parameters ldaphost,ldapport,ldapbinddn, ldapbindnpassword.
*/
public CMSLDAP(String h, String p, String dn, String pwd) {
HOST = h;
@@ -68,7 +68,7 @@ public class CMSLDAP {
}
/**
- * Connect to ldap server
+ * Connect to ldap server
*/
public boolean connect() {
@@ -110,13 +110,12 @@ public class CMSLDAP {
}
/**
- * Search for certificaterevocationList attribute. Takes basedn and filter
- * as parameters
- */
+ * Search for certificaterevocationList attribute. Takes basedn and filter as parameters
+ */
- public boolean searchCRL(String basedn, String filter) throws LDAPException {
+ public boolean searchCRL(String basedn, String filter) throws LDAPException {
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "certificateRevocationList;binary" };
+ String getAttrs[] = { "certificateRevocationList;binary"};
LDAPSearchResults results = conn.search(basedn, searchScope, filter,
getAttrs, false);
@@ -128,8 +127,8 @@ public class CMSLDAP {
LDAPEntry entry = (LDAPEntry) results.nextElement();
System.out.println(entry.getDN());
- LDAPAttribute anAttr = entry
- .getAttribute("certificateRevocationList;binary");
+ LDAPAttribute anAttr = entry.getAttribute(
+ "certificateRevocationList;binary");
if (anAttr == null) {
System.out.println("Attribute not found ");
@@ -147,10 +146,11 @@ public class CMSLDAP {
* Search for attriburte usercertificate. Takes parameters basedn and filter
*/
- public boolean searchUserCert(String basedn, String filter)
- throws LDAPException {
+
+
+ public boolean searchUserCert(String basedn, String filter) throws LDAPException {
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "usercertificate;binary" };
+ String getAttrs[] = { "usercertificate;binary"};
LDAPSearchResults results = conn.search(basedn, searchScope, filter,
getAttrs, false);
@@ -177,17 +177,18 @@ public class CMSLDAP {
}
/**
- * Adds a user to direcrtory server . Takes parameters basedn, cn,sn,uid and
- * passwd
+ * Adds a user to direcrtory server . Takes parameters basedn, cn,sn,uid and passwd
*/
- public boolean userAdd(String basedn, String cn, String sn, String uid,
- String pwd) {
+ public boolean userAdd(String basedn, String cn, String sn, String uid, String pwd) {
try {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- attrSet.add(new LDAPAttribute("objectclass", new String[] { "top",
- "person", "organizationalPerson", "inetorgperson" }));
+ attrSet.add(
+ new LDAPAttribute("objectclass",
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson"}));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -215,8 +216,8 @@ public class CMSLDAP {
ByteArrayInputStream s = new ByteArrayInputStream(cpack);
System.out.println("Building certificate :" + cpack);
- java.security.cert.X509Certificate the_cert = (java.security.cert.X509Certificate) cf
- .generateCertificate(s);
+ java.security.cert.X509Certificate the_cert = (
+ java.security.cert.X509Certificate) cf.generateCertificate(s);
return the_cert;
} catch (Exception e) {
@@ -235,7 +236,7 @@ public class CMSLDAP {
val += ',';
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -243,8 +244,8 @@ public class CMSLDAP {
}
/**
- * Returns the SerialNumber;issuerDN;SubjectDN string. Takes certificate as
- * parameter
+ * Returns the SerialNumber;issuerDN;SubjectDN string.
+ * Takes certificate as parameter
*/
public String getCertificateString(X509Certificate cert) {
@@ -268,19 +269,19 @@ public class CMSLDAP {
}
/**
- * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate
- * as parameters.
+ * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters.
*/
- public boolean CMSuserAdd(String cn, String sn, String uid, String pwd,
- byte[] certpack) {
+ public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, byte[] certpack) {
try {
X509Certificate cert = getXCertificate(certpack);
-
+
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- attrSet.add(new LDAPAttribute("objectclass", new String[] { "top",
- "person", "organizationalPerson", "inetorgperson",
- "cmsuser" }));
+ attrSet.add(
+ new LDAPAttribute("objectclass",
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson", "cmsuser"}));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -289,8 +290,8 @@ public class CMSLDAP {
attrSet.add(new LDAPAttribute("usertype", "sub"));
attrSet.add(new LDAPAttribute("userstate", "1"));
- attrSet.add(new LDAPAttribute("description",
- getCertificateString(cert)));
+ attrSet.add(
+ new LDAPAttribute("description", getCertificateString(cert)));
LDAPAttribute attrCertBin = new LDAPAttribute("usercertificate");
attrCertBin.addValue(cert.getEncoded());
@@ -311,19 +312,19 @@ public class CMSLDAP {
}
/**
- * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate
- * as parameters.
+ * Adds a user of objectclass cmsuser . Takes cn,sn,uid,password,certificate as parameters.
*/
- public boolean CMSuserAdd(String cn, String sn, String uid, String pwd,
- X509Certificate cert) {
+ public boolean CMSuserAdd(String cn, String sn, String uid, String pwd, X509Certificate cert) {
try {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- attrSet.add(new LDAPAttribute("objectclass", new String[] { "top",
- "person", "organizationalPerson", "inetorgperson",
- "cmsuser" }));
+ attrSet.add(
+ new LDAPAttribute("objectclass",
+ new String[] {
+ "top", "person", "organizationalPerson",
+ "inetorgperson", "cmsuser"}));
attrSet.add(new LDAPAttribute("cn", cn));
attrSet.add(new LDAPAttribute("mail", uid + "@netscape.com"));
attrSet.add(new LDAPAttribute("userpassword", pwd));
@@ -332,8 +333,8 @@ public class CMSLDAP {
attrSet.add(new LDAPAttribute("usertype", "sub"));
attrSet.add(new LDAPAttribute("userstate", "1"));
- attrSet.add(new LDAPAttribute("description",
- getCertificateString(cert)));
+ attrSet.add(
+ new LDAPAttribute("description", getCertificateString(cert)));
LDAPAttribute attrCertBin = new LDAPAttribute("usercertificate");
@@ -355,14 +356,14 @@ public class CMSLDAP {
}
/**
- * adds a cms user to Trusted Manager Group. Takes uid as parameter.
+ * adds a cms user to Trusted Manager Group. Takes uid as parameter.
*/
public boolean addCMSUserToTMGroup(String uid) {
try {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- LDAPAttribute um = new LDAPAttribute("uniquemember", "uid=" + uid
- + ",ou=People,o=NetscapeCertificateServer");
+ LDAPAttribute um = new LDAPAttribute("uniquemember",
+ "uid=" + uid + ",ou=People,o=NetscapeCertificateServer");
attrSet.add(um);
LDAPModification gr = new LDAPModification(LDAPModification.ADD, um);
@@ -380,8 +381,7 @@ public class CMSLDAP {
}
/**
- * adds a cms user to Agent Group. Takes subsytem (ca/ra/ocsp/kra) and uid
- * as parameters .
+ * adds a cms user to Agent Group. Takes subsytem (ca/ra/ocsp/kra) and uid as parameters .
*/
public boolean addCMSUserToAgentGroup(String subsystem, String uid) {
@@ -405,11 +405,11 @@ public class CMSLDAP {
}
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- LDAPAttribute um = new LDAPAttribute("uniquemember", "uid=" + uid
- + ",ou=People,o=NetscapeCertificateServer");
+ LDAPAttribute um = new LDAPAttribute("uniquemember",
+ "uid=" + uid + ",ou=People,o=NetscapeCertificateServer");
- System.out.println("uid=" + uid
- + ",ou=People,o=NetscapeCertificateServer");
+ System.out.println(
+ "uid=" + uid + ",ou=People,o=NetscapeCertificateServer");
attrSet.add(um);
LDAPModification gr = new LDAPModification(LDAPModification.ADD, um);
@@ -426,7 +426,7 @@ public class CMSLDAP {
}
/**
- * Will trun of SSL in LDAP server
+ * Will trun of SSL in LDAP server
**/
public boolean TurnOffSSL() {
@@ -437,10 +437,10 @@ public class CMSLDAP {
LDAPAttribute ssl3ciphers = new LDAPAttribute("nsssl3ciphers", "");
LDAPAttribute kfile = new LDAPAttribute("nskeyfile", "alias/");
LDAPAttribute cfile = new LDAPAttribute("nscertfile", "alias/");
- LDAPAttribute cauth = new LDAPAttribute("nssslclientauth",
- "allowed");
+ LDAPAttribute cauth = new LDAPAttribute("nssslclientauth", "allowed");
+
+ // conn.delete("cn=RSA,cn=encryption,cn=config");
- // conn.delete("cn=RSA,cn=encryption,cn=config");
mods.add(LDAPModification.REPLACE, ssl3);
mods.add(LDAPModification.DELETE, ssl3ciphers);
@@ -473,10 +473,9 @@ public class CMSLDAP {
}
/**
- * Will Turn ON SSL in LDAP server . Takes certPrefix, certificatenickanme
- * and sslport as parameters.
+ * Will Turn ON SSL in LDAP server . Takes certPrefix, certificatenickanme and sslport as parameters.
**/
-
+
public boolean TurnOnSSL(String certPrefix, String certName, String sslport) {
String dn;
String CIPHERS = "-rsa_null_md5,+rsa_fips_3des_sha,+rsa_fips_des_sha,+rsa_3des_sha,+rsa_rc4_128_md5,+rsa_des_sha,+rsa_rc2_40_md5,+rsa_rc4_40_md5";
@@ -484,8 +483,8 @@ public class CMSLDAP {
try {
boolean found = false;
int searchScope = LDAPv2.SCOPE_SUB;
- String getAttrs[] = { "nssslactivation" };
-
+ String getAttrs[] = { "nssslactivation"};
+
LDAPModificationSet mods = new LDAPModificationSet();
LDAPAttribute sec = new LDAPAttribute("nsslapd-security", "on");
LDAPAttribute sp = new LDAPAttribute("nsslapd-securePort", sslport);
@@ -493,18 +492,17 @@ public class CMSLDAP {
mods.add(LDAPModification.REPLACE, sec);
mods.add(LDAPModification.REPLACE, sp);
conn.modify("cn=config", mods);
- mods.removeElementAt(1);
+ mods.removeElementAt(1);
mods.removeElementAt(0);
LDAPAttribute ssl3 = new LDAPAttribute("nsssl3", "on");
LDAPAttribute ssl3ciphers = new LDAPAttribute("nsssl3ciphers",
CIPHERS);
- LDAPAttribute kfile = new LDAPAttribute("nskeyfile", "alias/"
- + certPrefix + "-key3.db");
- LDAPAttribute cfile = new LDAPAttribute("nscertfile", "alias/"
- + certPrefix + "-cert7.db");
- LDAPAttribute cauth = new LDAPAttribute("nssslclientauth",
- "allowed");
+ LDAPAttribute kfile = new LDAPAttribute("nskeyfile",
+ "alias/" + certPrefix + "-key3.db");
+ LDAPAttribute cfile = new LDAPAttribute("nscertfile",
+ "alias/" + certPrefix + "-cert7.db");
+ LDAPAttribute cauth = new LDAPAttribute("nssslclientauth", "allowed");
mods.add(LDAPModification.REPLACE, ssl3);
mods.add(LDAPModification.REPLACE, ssl3ciphers);
@@ -513,14 +511,14 @@ public class CMSLDAP {
mods.add(LDAPModification.REPLACE, cauth);
conn.modify("cn=encryption,cn=config", mods);
- int i = 4;
+ int i = 4;
while (i >= 0) {
mods.removeElementAt(i);
i--;
}
- // conn.delete("cn=RSA,cn=encryption,cn=config");
+ // conn.delete("cn=RSA,cn=encryption,cn=config");
try {
LDAPSearchResults results = conn.search(
"cn=RSA,cn=encryption,cn=config", searchScope, null,
@@ -543,15 +541,16 @@ public class CMSLDAP {
} catch (Exception e1) {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
- attrSet.add(new LDAPAttribute("objectclass", new String[] {
- "top", "nsEncryptionModule" }));
+ attrSet.add(
+ new LDAPAttribute("objectclass",
+ new String[] { "top", "nsEncryptionModule"}));
attrSet.add(new LDAPAttribute("cn", "RSA"));
- attrSet.add(new LDAPAttribute("nsssltoken",
- "internal (software)"));
+ attrSet.add(
+ new LDAPAttribute("nsssltoken", "internal (software)"));
attrSet.add(new LDAPAttribute("nssslactivation", "on"));
attrSet.add(new LDAPAttribute("nssslpersonalityssl", certName));
- LDAPEntry entry = new LDAPEntry(
- "cn=RSA,cn=encryption,cn=config", attrSet);
+ LDAPEntry entry = new LDAPEntry("cn=RSA,cn=encryption,cn=config",
+ attrSet);
conn.add(entry);
}
@@ -583,13 +582,13 @@ public class CMSLDAP {
System.out.println(HOST + PORT + DN + PASSWORD + BASEDN);
CMSLDAP caIdb = new CMSLDAP(HOST, PORT, DN, PASSWORD);
- /*
- * FileInputStream fis = new FileInputStream("t1"); DataInputStream
- * dis = new DataInputStream(fis);
- *
- * byte[] bytes = new byte[dis.available()]; dis.readFully(bytes);
- *
- * // bytes=s.getBytes();
+ /* FileInputStream fis = new FileInputStream("t1");
+ DataInputStream dis = new DataInputStream(fis);
+
+ byte[] bytes = new byte[dis.available()];
+ dis.readFully(bytes);
+
+ // bytes=s.getBytes();
*/
if (!caIdb.connect()) {
@@ -602,22 +601,17 @@ public class CMSLDAP {
// if(!caIdb.searchUserCert("o=mcom.com","uid=test"))
// System.out.println("USer cert is not published");
-
- // if (!caIdb.CMSuserAdd("ra-trust"
- // ,"ra-trust","ra-trust","netscape",bytes))
+
+ // if (!caIdb.CMSuserAdd("ra-trust" ,"ra-trust","ra-trust","netscape",bytes))
// {System.out.println("Trusted MAnager user Could not be add ");}
// if(!caIdb.addCMSUserToTMGroup("ra-trust"))
- // {System.out.println("CMS user Could not be added to Trusted manager group ");
- // }
+ // {System.out.println("CMS user Could not be added to Trusted manager group "); }
// if(!caIdb.addCMSUserToAgentGroup("ra","ra-agent"))
- // {System.out.println("CMS user Could not be added to Trusted manager group ");
- // }
- /*
- * if(!caIdb.userAdd(BASEDN,"raeetest1","raeetest1","raeetest1",
- * "netscape")) {System.out.println(
- * "CMS user Could not be added to Trusted manager group "); }
+ // {System.out.println("CMS user Could not be added to Trusted manager group "); }
+ /* if(!caIdb.userAdd(BASEDN,"raeetest1","raeetest1","raeetest1","netscape"))
+ {System.out.println("CMS user Could not be added to Trusted manager group "); }
*/
} catch (Exception e) {
@@ -626,3 +620,4 @@ public class CMSLDAP {
}
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
index 90e3aef7..bae3e420 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -41,44 +40,45 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
+
/**
- * The <code>Properties</code> class represents a persistent set of properties.
- * The <code>Properties</code> can be saved to a stream or loaded from a stream.
- * Each key and its corresponding value in the property list is a string.
+ * The <code>Properties</code> class represents a persistent set of
+ * properties. The <code>Properties</code> can be saved to a stream
+ * or loaded from a stream. Each key and its corresponding value in
+ * the property list is a string.
* <p>
- * A property list can contain another property list as its "defaults"; this
- * second property list is searched if the property key is not found in the
- * original property list.
+ * A property list can contain another property list as its
+ * "defaults"; this second property list is searched if
+ * the property key is not found in the original property list.
* <p>
* Because <code>Properties</code> inherits from <code>Hashtable</code>, the
* <code>put</code> and <code>putAll</code> methods can be applied to a
- * <code>Properties</code> object. Their use is strongly discouraged as they
+ * <code>Properties</code> object. Their use is strongly discouraged as they
* allow the caller to insert entries whose keys or values are not
- * <code>Strings</code>. The <code>setProperty</code> method should be used
- * instead. If the <code>store</code> or <code>save</code> method is called on a
- * "compromised" <code>Properties</code> object that contains a non-
- * <code>String</code> key or value, the call will fail.
+ * <code>Strings</code>. The <code>setProperty</code> method should be used
+ * instead. If the <code>store</code> or <code>save</code> method is called
+ * on a "compromised" <code>Properties</code> object that contains a
+ * non-<code>String</code> key or value, the call will fail.
* <p>
- * <a name="encoding"></a> When saving properties to a stream or loading them
- * from a stream, the ISO 8859-1 character encoding is used. For characters that
- * cannot be directly represented in this encoding, <a
- * href="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode
- * escapes</a> are used; however, only a single 'u' character is allowed in an
- * escape sequence. The native2ascii tool can be used to convert property files
- * to and from other character encodings.
- *
- * @see <a href="../../../tooldocs/solaris/native2ascii.html">native2ascii tool
- * for Solaris</a>
- * @see <a href="../../../tooldocs/win32/native2ascii.html">native2ascii tool
- * for Windows</a>
+ * <a name="encoding"></a>
+ * When saving properties to a stream or loading them from a stream, the
+ * ISO 8859-1 character encoding is used. For characters that cannot be directly
+ * represented in this encoding,
+ * <a href="http://java.sun.com/docs/books/jls/html/3.doc.html#100850">Unicode escapes</a>
+ * are used; however, only a single 'u' character is allowed in an escape sequence.
+ * The native2ascii tool can be used to convert property files to and from
+ * other character encodings.
*
- * @author Arthur van Hoff
- * @author Michael McCloskey
+ * @see <a href="../../../tooldocs/solaris/native2ascii.html">native2ascii tool for Solaris</a>
+ * @see <a href="../../../tooldocs/win32/native2ascii.html">native2ascii tool for Windows</a>
+ *
+ * @author Arthur van Hoff
+ * @author Michael McCloskey
* @version 1.60, 02/02/00
- * @since JDK1.0
+ * @since JDK1.0
*/
-class CMSProperties extends Hashtable<String, String> {
+class CMSProperties extends Hashtable<String,String> {
/**
* use serialVersionUID from JDK 1.1.X for interoperability
@@ -86,9 +86,9 @@ class CMSProperties extends Hashtable<String, String> {
private static final long serialVersionUID = 4112578634029874840L;
/**
- * A property list that contains default values for any keys not found in
- * this property list.
- *
+ * A property list that contains default values for any keys not
+ * found in this property list.
+ *
* @serial
*/
protected CMSProperties defaults;
@@ -102,22 +102,22 @@ class CMSProperties extends Hashtable<String, String> {
/**
* Creates an empty property list with the specified defaults.
- *
- * @param defaults the defaults.
+ *
+ * @param defaults the defaults.
*/
public CMSProperties(CMSProperties defaults) {
this.defaults = defaults;
}
/**
- * Calls the hashtable method <code>put</code>. Provided for parallelism
- * with the <tt>getProperty</tt> method. Enforces use of strings for
- * property keys and values.
- *
+ * Calls the hashtable method <code>put</code>. Provided for
+ * parallelism with the <tt>getProperty</tt> method. Enforces use of
+ * strings for property keys and values.
+ *
* @param key the key to be placed into this property list.
* @param value the value corresponding to <tt>key</tt>.
* @see #getProperty
- * @since 1.2
+ * @since 1.2
*/
public synchronized Object setProperty(String key, String value) {
return put(key, value);
@@ -132,91 +132,83 @@ class CMSProperties extends Hashtable<String, String> {
private static final String whiteSpaceChars = " \t\r\n\f";
/**
- * Reads a property list (key and element pairs) from the input stream. The
- * stream is assumed to be using the ISO 8859-1 character encoding.
+ * Reads a property list (key and element pairs) from the input stream.
+ * The stream is assumed to be using the ISO 8859-1 character encoding.
* <p>
- * Every property occupies one line of the input stream. Each line is
- * terminated by a line terminator (<code>\n</code> or <code>\r</code> or
- * <code>\r\n</code>). Lines from the input stream are processed until end
- * of file is reached on the input stream.
+ * Every property occupies one line of the input stream. Each line
+ * is terminated by a line terminator (<code>\n</code> or <code>\r</code>
+ * or <code>\r\n</code>). Lines from the input stream are processed until
+ * end of file is reached on the input stream.
* <p>
* A line that contains only whitespace or whose first non-whitespace
- * character is an ASCII <code>#</code> or <code>!</code> is ignored (thus,
- * <code>#</code> or <code>!</code> indicate comment lines).
+ * character is an ASCII <code>#</code> or <code>!</code> is ignored
+ * (thus, <code>#</code> or <code>!</code> indicate comment lines).
* <p>
* Every line other than a blank line or a comment line describes one
* property to be added to the table (except that if a line ends with \,
- * then the following line, if it exists, is treated as a continuation line,
- * as described below). The key consists of all the characters in the line
- * starting with the first non-whitespace character and up to, but not
- * including, the first ASCII <code>=</code>, <code>:</code>, or whitespace
- * character. All of the key termination characters may be included in the
- * key by preceding them with a \. Any whitespace after the key is skipped;
- * if the first non-whitespace character after the key is <code>=</code> or
- * <code>:</code>, then it is ignored and any whitespace characters after it
- * are also skipped. All remaining characters on the line become part of the
- * associated element string. Within the element string, the ASCII escape
- * sequences <code>\t</code>, <code>\n</code>, <code>\r</code>,
- * <code>\\</code>, <code>\"</code>, <code>\'</code>, <code>\ &#32;</code>
- * &#32;(a backslash and a space), and <code>&#92;u</code><i>xxxx</i> are
- * recognized and converted to single characters. Moreover, if the last
- * character on the line is <code>\</code>, then the next line is treated as
- * a continuation of the current line; the <code>\</code> and line
- * terminator are simply discarded, and any leading whitespace characters on
- * the continuation line are also discarded and are not part of the element
- * string.
+ * then the following line, if it exists, is treated as a continuation
+ * line, as described
+ * below). The key consists of all the characters in the line starting
+ * with the first non-whitespace character and up to, but not including,
+ * the first ASCII <code>=</code>, <code>:</code>, or whitespace
+ * character. All of the key termination characters may be included in
+ * the key by preceding them with a \.
+ * Any whitespace after the key is skipped; if the first non-whitespace
+ * character after the key is <code>=</code> or <code>:</code>, then it
+ * is ignored and any whitespace characters after it are also skipped.
+ * All remaining characters on the line become part of the associated
+ * element string. Within the element string, the ASCII
+ * escape sequences <code>\t</code>, <code>\n</code>,
+ * <code>\r</code>, <code>\\</code>, <code>\"</code>, <code>\'</code>,
+ * <code>\ &#32;</code> &#32;(a backslash and a space), and
+ * <code>&#92;u</code><i>xxxx</i> are recognized and converted to single
+ * characters. Moreover, if the last character on the line is
+ * <code>\</code>, then the next line is treated as a continuation of the
+ * current line; the <code>\</code> and line terminator are simply
+ * discarded, and any leading whitespace characters on the continuation
+ * line are also discarded and are not part of the element string.
* <p>
* As an example, each of the following four lines specifies the key
* <code>"Truth"</code> and the associated element value
* <code>"Beauty"</code>:
* <p>
- *
* <pre>
* Truth = Beauty
- * Truth:Beauty
+ * Truth:Beauty
* Truth :Beauty
* </pre>
- *
- * As another example, the following three lines specify a single property:
+ * As another example, the following three lines specify a single
+ * property:
* <p>
- *
* <pre>
* fruits apple, banana, pear, \
* cantaloupe, watermelon, \
* kiwi, mango
* </pre>
- *
* The key is <code>"fruits"</code> and the associated element is:
* <p>
- *
- * <pre>
- * &quot;apple, banana, pear, cantaloupe, watermelon,kiwi, mango&quot;
- * </pre>
- *
- * Note that a space appears before each <code>\</code> so that a space will
- * appear after each comma in the final result; the <code>\</code>, line
- * terminator, and leading whitespace on the continuation line are merely
- * discarded and are <i>not</i> replaced by one or more other characters.
+ * <pre>"apple, banana, pear, cantaloupe, watermelon,kiwi, mango"</pre>
+ * Note that a space appears before each <code>\</code> so that a space
+ * will appear after each comma in the final result; the <code>\</code>,
+ * line terminator, and leading whitespace on the continuation line are
+ * merely discarded and are <i>not</i> replaced by one or more other
+ * characters.
* <p>
* As a third example, the line:
* <p>
- *
- * <pre>
- * cheeses
+ * <pre>cheeses
* </pre>
- *
* specifies that the key is <code>"cheeses"</code> and the associated
- * element is the empty string.
- * <p>
- *
- * @param inStream the input stream.
- * @exception IOException if an error occurred when reading from the input
- * stream.
+ * element is the empty string.<p>
+ *
+ * @param inStream the input stream.
+ * @exception IOException if an error occurred when reading from the
+ * input stream.
*/
public synchronized void load(InputStream inStream) throws IOException {
- BufferedReader in = new BufferedReader(new InputStreamReader(inStream,
- "8859_1"));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(inStream, "8859_1"));
while (true) {
// Get next line
@@ -237,14 +229,14 @@ class CMSProperties extends Hashtable<String, String> {
if (nextLine == null) {
nextLine = new String("");
}
- String loppedLine = line
- .substring(0, line.length() - 1);
+ String loppedLine = line.substring(0, line.length() - 1);
// Advance beyond whitespace on new line
int startIndex = 0;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++) {
- if (whiteSpaceChars.indexOf(nextLine
- .charAt(startIndex)) == -1) {
+ if (whiteSpaceChars.indexOf(
+ nextLine.charAt(startIndex))
+ == -1) {
break;
}
}
@@ -285,29 +277,33 @@ class CMSProperties extends Hashtable<String, String> {
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++) {
- if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
+ if (whiteSpaceChars.indexOf(line.charAt(valueIndex))
+ == -1) {
break;
}
}
// Skip over one non whitespace key value separators if any
if (valueIndex < len) {
- if (strictKeyValueSeparators.indexOf(line
- .charAt(valueIndex)) != -1) {
+ if (strictKeyValueSeparators.indexOf(
+ line.charAt(valueIndex))
+ != -1) {
valueIndex++;
}
}
// Skip over white space after other separators if any
while (valueIndex < len) {
- if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1) {
+ if (whiteSpaceChars.indexOf(line.charAt(valueIndex))
+ == -1) {
break;
}
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
- String value = (separatorIndex < len) ? line.substring(
- valueIndex, len) : "";
+ String value = (separatorIndex < len)
+ ? line.substring(valueIndex, len)
+ : "";
// Convert then store key and value
key = loadConvert(key);
@@ -319,8 +315,8 @@ class CMSProperties extends Hashtable<String, String> {
}
/*
- * Returns true if the given line is a line that must be appended to the
- * next line
+ * Returns true if the given line is a line that must
+ * be appended to the next line
*/
private boolean continueLine(String line) {
int slashCount = 0;
@@ -333,8 +329,8 @@ class CMSProperties extends Hashtable<String, String> {
}
/*
- * Converts encoded &#92;uxxxx to unicode chars and changes special saved
- * chars to their original forms
+ * Converts encoded &#92;uxxxx to unicode chars
+ * and changes special saved chars to their original forms
*/
private String loadConvert(String theString) {
char aChar;
@@ -409,8 +405,9 @@ class CMSProperties extends Hashtable<String, String> {
}
/*
- * Converts unicodes to encoded &#92;uxxxx and writes out any of the
- * characters in specialSaveChars with a preceding slash
+ * Converts unicodes to encoded &#92;uxxxx
+ * and writes out any of the characters in specialSaveChars
+ * with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
@@ -421,7 +418,7 @@ class CMSProperties extends Hashtable<String, String> {
switch (aChar) {
case ' ':
- if (x == 0 || escapeSpace) {
+ if (x == 0 || escapeSpace) {
outBuffer.append('\\');
}
@@ -473,56 +470,53 @@ class CMSProperties extends Hashtable<String, String> {
}
/**
- * Calls the <code>store(OutputStream out, String header)</code> method and
- * suppresses IOExceptions that were thrown.
- *
+ * Calls the <code>store(OutputStream out, String header)</code> method
+ * and suppresses IOExceptions that were thrown.
+ *
* @deprecated This method does not throw an IOException if an I/O error
- * occurs while saving the property list. As of the Java 2
- * platform v1.2, the preferred way to save a properties list is
- * via the <code>store(OutputStream out,
+ * occurs while saving the property list. As of the Java 2 platform v1.2, the preferred
+ * way to save a properties list is via the <code>store(OutputStream out,
* String header)</code> method.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not
- * <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not <code>Strings</code>.
*/
public synchronized void save(OutputStream out, String header) {
try {
store(out, header);
- } catch (IOException e) {
- }
+ } catch (IOException e) {}
}
/**
* Writes this property list (key and element pairs) in this
* <code>Properties</code> table to the output stream in a format suitable
* for loading into a <code>Properties</code> table using the
- * <code>load</code> method. The stream is written using the ISO 8859-1
- * character encoding.
+ * <code>load</code> method.
+ * The stream is written using the ISO 8859-1 character encoding.
* <p>
- * Properties from the defaults table of this <code>Properties</code> table
- * (if any) are <i>not</i> written out by this method.
+ * Properties from the defaults table of this <code>Properties</code>
+ * table (if any) are <i>not</i> written out by this method.
* <p>
* If the header argument is not null, then an ASCII <code>#</code>
- * character, the header string, and a line separator are first written to
- * the output stream. Thus, the <code>header</code> can serve as an
+ * character, the header string, and a line separator are first written
+ * to the output stream. Thus, the <code>header</code> can serve as an
* identifying comment.
* <p>
* Next, a comment line is always written, consisting of an ASCII
- * <code>#</code> character, the current date and time (as if produced by
- * the <code>toString</code> method of <code>Date</code> for the current
- * time), and a line separator as generated by the Writer.
+ * <code>#</code> character, the current date and time (as if produced
+ * by the <code>toString</code> method of <code>Date</code> for the
+ * current time), and a line separator as generated by the Writer.
* <p>
* Then every entry in this <code>Properties</code> table is written out,
* one per line. For each entry the key string is written, then an ASCII
- * <code>=</code>, then the associated element string. Each character of the
- * element string is examined to see whether it should be rendered as an
- * escape sequence. The ASCII characters <code>\</code>, tab, newline, and
- * carriage return are written as <code>\\</code>, <code>\t</code>,
- * <code>\n</code>, and <code>\r</code>, respectively. Characters less than
- * <code>&#92;u0020</code> and characters greater than
+ * <code>=</code>, then the associated element string. Each character of
+ * the element string is examined to see whether it should be rendered as
+ * an escape sequence. The ASCII characters <code>\</code>, tab, newline,
+ * and carriage return are written as <code>\\</code>, <code>\t</code>,
+ * <code>\n</code>, and <code>\r</code>, respectively. Characters less
+ * than <code>&#92;u0020</code> and characters greater than
* <code>&#92;u007E</code> are written as <code>&#92;u</code><i>xxxx</i> for
* the appropriate hexadecimal value <i>xxxx</i>. Leading space characters,
* but not embedded or trailing space characters, are written with a
@@ -530,19 +524,18 @@ class CMSProperties extends Hashtable<String, String> {
* <code>!</code>, <code>=</code>, and <code>:</code> are written with a
* preceding slash to ensure that they are properly loaded.
* <p>
- * After the entries have been written, the output stream is flushed. The
+ * After the entries have been written, the output stream is flushed. The
* output stream remains open after this method returns.
- *
- * @param out an output stream.
- * @param header a description of the property list.
- * @exception IOException if writing this property list to the specified
- * output stream throws an <tt>IOException</tt>.
- * @exception ClassCastException if this <code>Properties</code> object
- * contains any keys or values that are not
- * <code>Strings</code>.
+ *
+ * @param out an output stream.
+ * @param header a description of the property list.
+ * @exception IOException if writing this property list to the specified
+ * output stream throws an <tt>IOException</tt>.
+ * @exception ClassCastException if this <code>Properties</code> object
+ * contains any keys or values that are not <code>Strings</code>.
*/
public synchronized void store(OutputStream out, String header)
- throws IOException {
+ throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
@@ -551,13 +544,12 @@ class CMSProperties extends Hashtable<String, String> {
}
writeln(awriter, "#" + new Date().toString());
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = get(key);
+ String key = e.nextElement();
+ String val = get(key);
key = saveConvert(key, true);
- /*
- * No need to escape embedded and trailing spaces for value, hence
+ /* No need to escape embedded and trailing spaces for value, hence
* pass false to flag.
*/
val = saveConvert(val, false);
@@ -576,18 +568,19 @@ class CMSProperties extends Hashtable<String, String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns
* <code>null</code> if the property is not found.
- *
- * @param key the property key.
- * @return the value in this property list with the specified key value.
- * @see #setProperty
- * @see #defaults
+ *
+ * @param key the property key.
+ * @return the value in this property list with the specified key value.
+ * @see #setProperty
+ * @see #defaults
*/
public String getProperty(String key) {
String oval = super.get(key);
- String sval = (oval instanceof String) ? oval : null;
+ String sval = (oval instanceof String) ? oval : null;
- return ((sval == null) && (defaults != null)) ? defaults
- .getProperty(key) : sval;
+ return ((sval == null) && (defaults != null))
+ ? defaults.getProperty(key)
+ : sval;
}
/**
@@ -595,13 +588,13 @@ class CMSProperties extends Hashtable<String, String> {
* If the key is not found in this property list, the default property list,
* and its defaults, recursively, are then checked. The method returns the
* default value argument if the property is not found.
- *
- * @param key the hashtable key.
- * @param defaultValue a default value.
- *
- * @return the value in this property list with the specified key value.
- * @see #setProperty
- * @see #defaults
+ *
+ * @param key the hashtable key.
+ * @param defaultValue a default value.
+ *
+ * @return the value in this property list with the specified key value.
+ * @see #setProperty
+ * @see #defaults
*/
public String getProperty(String key, String defaultValue) {
String val = getProperty(key);
@@ -612,11 +605,11 @@ class CMSProperties extends Hashtable<String, String> {
/**
* Returns an enumeration of all the keys in this property list, including
* the keys in the default property list.
- *
- * @return an enumeration of all the keys in this property list, including
- * the keys in the default property list.
- * @see java.util.Enumeration
- * @see java.util.Properties#defaults
+ *
+ * @return an enumeration of all the keys in this property list, including
+ * the keys in the default property list.
+ * @see java.util.Enumeration
+ * @see java.util.Properties#defaults
*/
public Enumeration<String> propertyNames() {
Hashtable<String, String> h = new Hashtable<String, String>();
@@ -626,10 +619,10 @@ class CMSProperties extends Hashtable<String, String> {
}
/**
- * Prints this property list out to the specified output stream. This method
- * is useful for debugging.
- *
- * @param out an output stream.
+ * Prints this property list out to the specified output stream.
+ * This method is useful for debugging.
+ *
+ * @param out an output stream.
*/
public void list(PrintStream out) {
out.println("-- listing properties --");
@@ -637,8 +630,8 @@ class CMSProperties extends Hashtable<String, String> {
enumerate(h);
for (Enumeration<String> e = h.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = h.get(key);
+ String key = e.nextElement();
+ String val = h.get(key);
if (val.length() > 40) {
val = val.substring(0, 37) + "...";
@@ -648,13 +641,13 @@ class CMSProperties extends Hashtable<String, String> {
}
/**
- * Prints this property list out to the specified output stream. This method
- * is useful for debugging.
- *
- * @param out an output stream.
- * @since JDK1.1
+ * Prints this property list out to the specified output stream.
+ * This method is useful for debugging.
+ *
+ * @param out an output stream.
+ * @since JDK1.1
*/
-
+
/*
* Rather than use an anonymous inner class to share common code, this
* method is duplicated in order to ensure that a non-1.1 compiler can
@@ -666,8 +659,8 @@ class CMSProperties extends Hashtable<String, String> {
enumerate(h);
for (Enumeration<String> e = h.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String val = h.get(key);
+ String key = e.nextElement();
+ String val = h.get(key);
if (val.length() > 40) {
val = val.substring(0, 37) + "...";
@@ -678,7 +671,6 @@ class CMSProperties extends Hashtable<String, String> {
/**
* Enumerates all key/value pairs in the specified hastable.
- *
* @param h the hashtable
*/
private synchronized void enumerate(Hashtable<String, String> h) {
@@ -686,7 +678,7 @@ class CMSProperties extends Hashtable<String, String> {
defaults.enumerate(h);
}
for (Enumeration<String> e = keys(); e.hasMoreElements();) {
- String key = e.nextElement();
+ String key = e.nextElement();
h.put(key, get(key));
}
@@ -694,14 +686,15 @@ class CMSProperties extends Hashtable<String, String> {
/**
* Convert a nibble to a hex character
- *
- * @param nibble the nibble to convert.
+ * @param nibble the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
}
/** A table of hex digits */
- private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6',
- '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ private static final char[] hexDigit = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
+ 'E', 'F'
+ };
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java b/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
index 3925dc10..593de383 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -25,8 +24,10 @@ import java.io.InputStreamReader;
import com.netscape.pkisilent.argparser.ArgParser;
import com.netscape.pkisilent.argparser.StringHolder;
+
/**
- * CS Test framework . This class starts and stops CS server from command line
+ * CS Test framework .
+ * This class starts and stops CS server from command line
*/
public class CMSTask {
@@ -37,8 +38,8 @@ public class CMSTask {
private Process p = null;
/**
- * Constructor . Takes CMS server root as parameter for example
- * (/export/qa/cert-jupiter2)
+ * Constructor . Takes CMS server root as parameter
+ * for example (/export/qa/cert-jupiter2)
**/
public CMSTask() {// do nothing
@@ -62,7 +63,7 @@ public class CMSTask {
try {
while ((s = br.readLine()) != null) {
- if (s.indexOf("started") > 0) {
+ if (s.indexOf("started") > 0) {
return true;
}
// do something
@@ -86,8 +87,8 @@ public class CMSTask {
System.out.println("Stopping Certificate System:");
p = r.exec(serverRoot + "/stop-cert");
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
@@ -110,8 +111,8 @@ public class CMSTask {
Runtime r = Runtime.getRuntime();
p = r.exec(serverRoot + "/restart-cert");
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
@@ -174,7 +175,7 @@ public class CMSTask {
// set variables
serverRoot = x_instance_root.value;
operation = x_operation.value;
-
+
boolean st = prof.task();
if (!st) {
@@ -185,5 +186,5 @@ public class CMSTask {
} // end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java b/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
index 9599eb6d..c636b0a1 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,8 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
+
public class CertificateRecord {
public String revokedOn = null;
@@ -41,4 +42,7 @@ public class CertificateRecord {
public CertificateRecord() {// Do nothing
}
-};
+}
+
+
+;
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java b/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
index 4376a1fa..46bd9664 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -65,11 +64,13 @@ import org.mozilla.jss.util.Password;
import com.netscape.osutil.OSUtil;
+
/**
- * CMS Test framework . Use this class to initalize,add a certificate ,generate
- * a certificate request from certificate database.
+ * CMS Test framework .
+ * Use this class to initalize,add a certificate ,generate a certificate request from certificate database.
*/
+
public class ComCrypto {
private String cdir, certnickname, keysize, keytype, tokenpwd;
@@ -97,20 +98,19 @@ public class ComCrypto {
private String certprefix = null;
- public ComCrypto() {
- };
+ public ComCrypto() {}
+ ;
/**
- * Constructor . Takes the parameter certificatedbdirectory , passwordfor
- * cert database, certificatenickname,keysize, keytype(RSA/DSA)
- *
+ * Constructor . Takes the parameter certificatedbdirectory , passwordfor cert database, certificatenickname,keysize, keytype(RSA/DSA)
* @param certdbdirectory.
- * @param certdbpassword
- * @param certnickname
+ * @param certdbpassword
+ * @param certnickname
* @param keysize (1024/2048/4096)
* @param keytype (RSA/DSA)
*/
+
public ComCrypto(String cd, String tpwd, String cn, String ks, String kt) {
cdir = cd;
tokenpwd = tpwd;
@@ -119,7 +119,7 @@ public class ComCrypto {
keytype = kt;
}
- // Set and Get functions
+ // Set and Get functions
public void setCertDir(String cd) {
cdir = cd;
@@ -158,9 +158,10 @@ public class ComCrypto {
}
/*
- * setTransportCert() should only be called when the calling profile needs
- * to do key archivals with the DRM and make sure the function
- * generateCRMFtransport() is called for the CRMF request generation part.
+ * setTransportCert() should only be called when the calling profile
+ * needs to do key archivals with the DRM and make sure the function
+ * generateCRMFtransport() is called for the CRMF request generation
+ * part.
*/
public void setTransportCert(String tcert) {
transportcert = tcert;
@@ -175,8 +176,7 @@ public class ComCrypto {
}
/**
- * Parses the Certificate and returns SubjectDN . Takes certificate as
- * parameter
+ * Parses the Certificate and returns SubjectDN . Takes certificate as parameter
*/
public String getCertificateString(X509Certificate cert) {
@@ -185,14 +185,15 @@ public class ComCrypto {
}
// note that it did not represent a certificate fully
- return cert.getVersion() + ";" + cert.getSerialNumber().toString()
- + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN();
+ return cert.getVersion() + ";" + cert.getSerialNumber().toString() + ";"
+ + cert.getIssuerDN() + ";" + cert.getSubjectDN();
}
/**
- * Finds and returns Certificate . Takes certificatenickname as parameter.
+ * Finds and returns Certificate . Takes certificatenickname as parameter.
*/
+
public X509Certificate findCert(String certname) {
try {
@@ -208,18 +209,17 @@ public class ComCrypto {
}
/**
- * Imports a certificate to Certificate Database. Takes certificate and
- * nickname as parameters.
+ * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters.
*/
+
public boolean importCert(X509Certificate xcert, String nickname) {
try {
- System.out.println("importCert x509 : importing with nickname: "
- + nickname);
+ System.out.println(
+ "importCert x509 : importing with nickname: " + nickname);
- InternalCertificate cert2 = manager.importCertToPerm(xcert,
- nickname);
+ InternalCertificate cert2 = manager.importCertToPerm(xcert, nickname);
cert2.setSSLTrust(2);
return true;
@@ -232,10 +232,10 @@ public class ComCrypto {
}
/**
- * Imports a certificate to Certificate Database. Takes certificate and
- * nickname as parameters.
+ * Imports a certificate to Certificate Database. Takes certificate and nickname as parameters.
*/
+
public boolean importCert(String cpack, String cn) {
System.out.println("importCert string: importing with nickname: " + cn);
@@ -243,7 +243,7 @@ public class ComCrypto {
String tmp = normalize(cpack);
- if (DBlogin) {
+ if (DBlogin) {
System.out.println("Already logged into to DB");
}
@@ -251,22 +251,20 @@ public class ComCrypto {
System.out.println("Manager object is null");
}
- X509Certificate cert = manager
- .importCertPackage(tmp.getBytes(), cn);
+ X509Certificate cert = manager.importCertPackage(tmp.getBytes(), cn);
return true;
} catch (Exception e) {
- System.out.println("ERROR:exception importing cert "
- + e.getMessage());
+ System.out.println(
+ "ERROR:exception importing cert " + e.getMessage());
e.printStackTrace();
return false;
}
}
- /*
- * imports CA certificate
+ /* imports CA certificate
*/
public boolean importCACert(String cpack) {
@@ -274,10 +272,10 @@ public class ComCrypto {
try {
String tmp = normalize(cpack);
- if (DBlogin) {
+ if (DBlogin) {
System.out.println("Already logged into to DB");
}
-
+
if (manager == null) {
System.out.println("Manager object is null");
}
@@ -287,18 +285,18 @@ public class ComCrypto {
return true;
} catch (Exception e) {
- System.out.println("ERROR:exception importing cert "
- + e.getMessage());
+ System.out.println(
+ "ERROR:exception importing cert " + e.getMessage());
return false;
}
}
/**
- * Normalizes a given certificate string . Removes the extra \\ in the
- * certificate returned by CMS server.
+ * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
*/
+
public String normalize(String s) {
String val = "";
@@ -320,10 +318,10 @@ public class ComCrypto {
}
/**
- * Normalizes a given certificate string . Removes the extra \\ in the
- * certificate returned by CMS server.
+ * Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
*/
+
public String normalizeForLDAP(String s) {
String val = "";
@@ -348,6 +346,7 @@ public class ComCrypto {
* Convert to pkcs7 format
*/
+
public String pkcs7Convertcert(String s) {
String val = "";
@@ -397,13 +396,14 @@ public class ComCrypto {
* Creates a new certificate database
**/
+
public boolean CreateCertDB() {
return loginDB();
}
/**
- * Login to cert database
+ * Login to cert database
**/
public boolean loginDB() {
@@ -439,15 +439,15 @@ public class ComCrypto {
token.login(pass1);
pass1.clear();
- } catch (AlreadyInitializedException e) {
+ } catch (AlreadyInitializedException e) {
if (debug) {
System.out.println("Crypto manager already initialized");
}
} catch (Exception e) {
- try {
+ try {
if (!token.isLoggedIn()) {
token.initPassword(pass1, pass1);
- }
+ }
return true;
} catch (Exception er) {
System.err.println("some exception:" + e);
@@ -507,35 +507,35 @@ public class ComCrypto {
int num = 1;
long total_time = 0;
KeyPair pair = null;
-
- System.out.println("Debug : initialize crypto Manager");
+
+ System.out.println("Debug : initialize crypto Manager");
try {
// Step 1. initialize crypto Manager
- try {
+ try {
CryptoManager.initialize(cdir);
- } catch (Exception e) {
- // it is ok if it is already initialized
+ } catch (Exception e) {
+ // it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
}
- // Step 2 log into database
+ // Step 2 log into database
try {
System.out.println("Debug : before getInstance");
- manager = CryptoManager.getInstance();
+ manager = CryptoManager.getInstance();
String token_pwd = tokenpwd;
System.out.println("Debug : before get token");
- token = manager.getInternalKeyStorageToken();
- password = new Password(token_pwd.toCharArray());
+ token = manager.getInternalKeyStorageToken();
+ password = new Password(token_pwd.toCharArray());
System.out.println("Debug : before login password");
- token.login(password);
+ token.login(password);
System.out.println("Debug : after login password");
} catch (Exception e) {
@@ -546,10 +546,9 @@ public class ComCrypto {
}
}
- // Generating CRMF request
+ // Generating CRMF request
- KeyPairGenerator kg = token
- .getKeyPairGenerator(KeyPairAlgorithm.RSA);
+ KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
Integer x = new Integer(keysize);
int key_len = x.intValue();
@@ -557,7 +556,7 @@ public class ComCrypto {
kg.initialize(key_len);
// 1st key pair
- pair = kg.genKeyPair();
+ pair = kg.genKeyPair();
// create CRMF
CertTemplate certTemplate = new CertTemplate();
@@ -566,57 +565,53 @@ public class ComCrypto {
if (certnickname != null) {
X500Name name = new X500Name(certnickname);
- ByteArrayInputStream cs = new ByteArrayInputStream(
- name.getEncoded());
+ ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded());
Name n = (Name) Name.getTemplate().decode(cs);
certTemplate.setSubject(n);
}
- certTemplate
- .setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
+ certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
SEQUENCE seq = new SEQUENCE();
CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate,
seq);
- byte popdata[] = { 0x0, 0x3, 0x0 };
+ byte popdata[] = { 0x0, 0x3, 0x0};
- ProofOfPossession pop = ProofOfPossession
- .createKeyEncipherment(POPOPrivKey
- .createThisMessage(new BIT_STRING(popdata, 3)));
+ ProofOfPossession pop = ProofOfPossession.createKeyEncipherment(
+ POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3)));
CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null);
SEQUENCE s1 = new SEQUENCE();
-
- // 1st : Encryption key
+
+ // 1st : Encryption key
s1.addElement(crmfMsg);
// 2nd : Signing Key
-
+
if (dualkey) {
System.out.println("dualkey = true");
SEQUENCE seq1 = new SEQUENCE();
CertRequest certReqSigning = new CertRequest(new INTEGER(1),
certTemplate, seq1);
- CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop,
- null);
+ CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
s1.addElement(signingMsg);
- }
+ }
- byte encoded[] = ASN1Util.encode(s1);
+ byte encoded[] = ASN1Util.encode(s1);
- // BASE64Encoder encoder = new BASE64Encoder();
+ // BASE64Encoder encoder = new BASE64Encoder();
// String Req1 = encoder.encodeBuffer(encoded);
String Req1 = OSUtil.BtoA(encoded);
- // Set CRMF_REQUEST variable
+ // Set CRMF_REQUEST variable
CRMF_REQUEST = Req1;
System.out.println("CRMF_REQUEST = " + CRMF_REQUEST);
- } catch (Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: " + e.toString());
e.printStackTrace();
return null;
@@ -626,10 +621,10 @@ public class ComCrypto {
}
/*
- * This function is used to Generated CRMF requests wrapped with the
- * transport cert so that we can do key archival with the drm. This function
- * expects transportcert variable to be set in this class. Use
- * setTransportCert() to do the same.
+ * This function is used to Generated CRMF requests wrapped with the
+ * transport cert so that we can do key archival with the drm.
+ * This function expects transportcert variable to be set in this class.
+ * Use setTransportCert() to do the same.
*/
public String generateCRMFtransport() {
@@ -641,30 +636,30 @@ public class ComCrypto {
try {
// Step 1. initialize crypto Manager
- try {
+ try {
CryptoManager.initialize(cdir);
- } catch (Exception e) {
- // it is ok if it is already initialized
+ } catch (Exception e) {
+ // it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
}
- // Step 2 log into database
+ // Step 2 log into database
try {
System.out.println("Debug : before getInstance");
-
- manager = CryptoManager.getInstance();
+
+ manager = CryptoManager.getInstance();
String token_pwd = tokenpwd;
-
+
System.out.println("Debug : before get token");
-
- token = manager.getInternalKeyStorageToken();
- password = new Password(token_pwd.toCharArray());
+
+ token = manager.getInternalKeyStorageToken();
+ password = new Password(token_pwd.toCharArray());
System.out.println("Debug : before login password");
- token.login(password);
+ token.login(password);
System.out.println("Debug : after login password");
} catch (Exception e) {
@@ -674,10 +669,9 @@ public class ComCrypto {
token.initPassword(password, password);
}
}
-
+
// Key Pair Generation
- KeyPairGenerator kg = token
- .getKeyPairGenerator(KeyPairAlgorithm.RSA);
+ KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
Integer x = new Integer(keysize);
int key_len = x.intValue();
@@ -692,19 +686,19 @@ public class ComCrypto {
X509Certificate tcert = manager.importCACertPackage(transport);
- byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
+ byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3);
SymmetricKey sk = kg1.generate();
// wrap private key using session
- KeyWrapper wrapper1 = token
- .getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
+ KeyWrapper wrapper1 = token.getKeyWrapper(
+ KeyWrapAlgorithm.DES3_CBC_PAD);
wrapper1.initWrap(sk, new IVParameterSpec(iv));
- byte key_data[] = wrapper1
- .wrap((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate());
+ byte key_data[] = wrapper1.wrap((
+ org.mozilla.jss.crypto.PrivateKey) pair.getPrivate());
// wrap session using transport
KeyWrapper rsaWrap = token.getKeyWrapper(KeyWrapAlgorithm.RSA);
@@ -720,14 +714,12 @@ public class ComCrypto {
if (certnickname != null) {
X500Name name = new X500Name(certnickname);
- ByteArrayInputStream cs = new ByteArrayInputStream(
- name.getEncoded());
+ ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded());
Name n = (Name) Name.getTemplate().decode(cs);
certTemplate.setSubject(n);
}
- certTemplate
- .setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
+ certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic()));
// set extension
AlgorithmIdentifier algS = new AlgorithmIdentifier(
@@ -743,40 +735,38 @@ public class ComCrypto {
SEQUENCE seq = new SEQUENCE();
- seq.addElement(new AVA(
- new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opt));
+ seq.addElement(
+ new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opt));
CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate,
seq);
// Adding proof of possesion data
- byte popdata[] = { 0x0, 0x3, 0x0 };
- ProofOfPossession pop = ProofOfPossession
- .createKeyEncipherment(POPOPrivKey
- .createThisMessage(new BIT_STRING(popdata, 3)));
+ byte popdata[] = { 0x0, 0x3, 0x0};
+ ProofOfPossession pop = ProofOfPossession.createKeyEncipherment(
+ POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3)));
CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null);
SEQUENCE s1 = new SEQUENCE();
- // 1st : Encryption key
+ // 1st : Encryption key
s1.addElement(crmfMsg);
// 2nd : Signing Key
-
+
if (dualkey) {
System.out.println("dualkey = true");
SEQUENCE seq1 = new SEQUENCE();
CertRequest certReqSigning = new CertRequest(new INTEGER(1),
certTemplate, seq1);
- CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop,
- null);
+ CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null);
s1.addElement(signingMsg);
- }
+ }
byte encoded[] = ASN1Util.encode(s1);
-
+
// BASE64Encoder encoder = new BASE64Encoder();
// CRMF_REQUEST = encoder.encodeBuffer(encoded);
@@ -791,9 +781,9 @@ public class ComCrypto {
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
-
+
return CRMF_REQUEST;
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java b/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
index 146a4d93..6be4daf4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -36,9 +35,10 @@ import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
import org.mozilla.jss.ssl.SSLSocket;
import org.mozilla.jss.util.Password;
+
/**
- * CMS Test framework . Submits a requests to agent port with sslclient
- * authentication.
+ * CMS Test framework .
+ * Submits a requests to agent port with sslclient authentication.
*/
public class Con2Agent implements SSLClientCertificateSelectionCallback,
@@ -51,20 +51,18 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
private BufferedReader stdin = null;
private StringBuffer stdout = new StringBuffer();
- public Con2Agent() {
- }
+ public Con2Agent() {}
/**
- * Constructor. Takes hostname , portnumber , certificate nickname, token
- * password ,client certdb directory
- *
- * @param hostname
+ *Constructor. Takes hostname , portnumber , certificate nickname, token password ,client certdb directory
+ * @param hostname
* @param portnumber
* @param agent cert nickname
- * @param token password
+ * @param token password
* @param certdb directory
*/
+
public Con2Agent(String hs, int p, String cname, String tpwd, String cdir) {
host = hs;
port = p;
@@ -73,8 +71,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
certdir = cdir;
}
- public boolean approve(X509Certificate x509,
- SSLCertificateApprovalCallback.ValidityStatus status) {
+ public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) {
return true;
}
@@ -98,10 +95,10 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
- // Get and Set methods
+ // Get and Set methods
/*
- * Get the page returned by the server
+ * Get the page returned by the server
*/
public StringBuffer getPage() {
@@ -109,7 +106,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set the query string to be submitted to the server
+ * Set the query string to be submitted to the server
*/
public void setQueryString(String qu) {
@@ -117,7 +114,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set token password
+ *Set token password
*/
public void setTokenPassword(String pwd) {
@@ -141,7 +138,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * set Agent port number
+ * set Agent port number
*/
public void setPort(int p) {
@@ -149,7 +146,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set Agent cert nickname
+ * Set Agent cert nickname
*/
public void setCertNickName(String cname) {
@@ -157,21 +154,21 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
/*
- * Set action URL
+ * Set action URL
*/
public void setActionURL(String url) {
ACTIONURL = url;
}
- // Submit requests
+ // Submit requests
public boolean Send() {
boolean st = false;
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -179,8 +176,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
System.out.println("Con2Agent.java: host = " + host);
System.out.println("Con2Agent.java: port = " + port);
- System.out
- .println("Con2Agent.java: certnickname = " + certnickname);
+ System.out.println("Con2Agent.java: certnickname = " + certnickname);
socket.setClientCertNickname(certnickname);
System.out.println("Connected to the socket");
@@ -188,7 +184,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
OutputStream rawos = socket.getOutputStream();
BufferedOutputStream os = new BufferedOutputStream(rawos);
PrintStream ps = new PrintStream(os);
-
+
System.out.println(ACTIONURL);
System.out.println("Query :" + query);
ps.println("POST " + ACTIONURL + " HTTP/1.0");
@@ -200,8 +196,8 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
ps.println("\r");
ps.flush();
os.flush();
- BufferedReader stdin1 = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ BufferedReader stdin1 = new BufferedReader(
+ new InputStreamReader(socket.getInputStream()));
String line;
while ((line = stdin1.readLine()) != null) {
@@ -209,9 +205,8 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
System.out.println(line);
}
- // Send Connection: close to let the server close the connection.
- // Else the socket on the server side continues to remain in
- // TIME_WAIT state
+ // Send Connection: close to let the server close the connection.
+ // Else the socket on the server side continues to remain in TIME_WAIT state
ps.println("Connection: close");
ps.flush();
@@ -244,13 +239,12 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
System.out.println("Step 1: Initializing CryptoManager");
CryptoManager.initialize(certdir);
-
- System.out.println("Step 2: Login to Cert Database");
+
+ System.out.println("Step 2: Login to Cert Database");
manager = CryptoManager.getInstance();
- CryptoToken token = (PK11Token) manager
- .getInternalKeyStorageToken();
+ CryptoToken token = (PK11Token) manager.getInternalKeyStorageToken();
- if (token.isLoggedIn()) {
+ if (token.isLoggedIn()) {
System.out.println("Con2Agent: Logged in incorrect");
}
@@ -262,12 +256,12 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
pass1 = new Password((char[]) passchar1.clone());
token.login(pass1);
- X509Certificate cert2 = manager.findCertByNickname(certnickname);
+ X509Certificate cert2 = manager.findCertByNickname(certnickname);
certname = cert2.getNickname();
return true;
- } catch (AlreadyInitializedException e) {
+ } catch (AlreadyInitializedException e) {
System.out.println("Crypto manager already initialized");
return true;
} catch (NumberFormatException e) {
@@ -282,7 +276,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
e.printStackTrace();
return false;
}
-
+
}
public boolean Send_withGET() {
@@ -291,7 +285,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -303,7 +297,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
OutputStream rawos = socket.getOutputStream();
BufferedOutputStream os = new BufferedOutputStream(rawos);
PrintStream ps = new PrintStream(os);
-
+
System.out.println("Query in con2agent :" + query);
System.out.println("ACTIONURL in con2agent : " + ACTIONURL);
@@ -312,8 +306,8 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
ps.println("\r");
ps.flush();
os.flush();
- BufferedReader stdin2 = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ BufferedReader stdin2 = new BufferedReader(
+ new InputStreamReader(socket.getInputStream()));
String line;
while ((line = stdin2.readLine()) != null) {
@@ -332,4 +326,4 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
}
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java b/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
index ab52d7b4..59820fe7 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,7 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,13 +29,15 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
+
+
/**
- * CMS Test framework - Legacyenrollment forms for Directory based enrollmnet
- * and Portal based enrollment . Certificate issuance through Legacy Directory
- * based enrollment and Portal based enrollment form.
- * <P>
+ * CMS Test framework - Legacyenrollment forms for Directory based enrollmnet and Portal based enrollment .
+ * Certificate issuance through Legacy Directory based enrollment and Portal based enrollment form.
+ *<P>
*/
+
public class DirEnroll extends TestClient {
private int i;
@@ -51,8 +53,7 @@ public class DirEnroll extends TestClient {
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- *
- * @param propfilename name of the parameter file
+ * @param propfilename name of the parameter file
*/
public DirEnroll(String pfile) {
@@ -62,7 +63,6 @@ public class DirEnroll extends TestClient {
/**
* Constructor. Takes hostname , EESSLportnumber as parameter
* <p>
- *
* @param hostname
* @param portnumber
*/
@@ -73,11 +73,8 @@ public class DirEnroll extends TestClient {
}
/**
- * Constructor. Takes
- * hostname,EESSLportnumber,uid,password,certdbdirectorypath
- * ,certdbpassword,certificatenickname,keysize,teytype
+ * Constructor. Takes hostname,EESSLportnumber,uid,password,certdbdirectorypath,certdbpassword,certificatenickname,keysize,teytype
* <p>
- *
* @param hostname
* @param portnumber
* @param subjectdn
@@ -85,9 +82,8 @@ public class DirEnroll extends TestClient {
* @param adminpassword
*/
- public DirEnroll(String hs, String p, String uid, String pw,
- String certdir, String certtokenpwd, String nickname, String ksz,
- String kt) {
+
+ public DirEnroll(String hs, String p, String uid, String pw, String certdir, String certtokenpwd, String nickname, String ksz, String kt) {
host = hs;
ports = p;
@@ -100,18 +96,18 @@ public class DirEnroll extends TestClient {
keytype = "RSA";
}
- // Set and Get functions
+ // Set and Get functions
/**
- * Use this method to set User Info
- */
+ * Use this method to set User Info
+ */
public void setUIDInfo(String uid, String pw) {
UID = uid;
PWD = pw;
}
/**
- * Returns a string "UserDir" / "Portal"
+ * Returns a string "UserDir" / "Portal"
*/
public String getAuthenticator() {
@@ -119,27 +115,26 @@ public class DirEnroll extends TestClient {
}
/**
- * Valid values for s - UserDir for Directory based Authntication Portal for
- * Portal based Authentication
+ * Valid values for s - UserDir for Directory based Authntication
+ * Portal for Portal based Authentication
*/
- public void setAuthenticator(String s) {
+ public void setAuthenticator(String s) {
Authenticator = s;
}
public boolean enroll_load() {
buildquery();
- return (Send());
+ return(Send());
}
private boolean pkcs10() {
- System.out.println(" In pkcs10 Keysize , key type " + keysize
- + keytype);
+ System.out.println(" In pkcs10 Keysize , key type " + keysize + keytype);
cCrypt.setCertDir(cdir);
cCrypt.setCertnickname("cn=test");
cCrypt.setKeySize(keysize);
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
-
+
cCrypt.setDebug(debug);
cCrypt.setGenerateRequest(true);
if (!cCrypt.generateRequest()) {
@@ -152,7 +147,7 @@ public class DirEnroll extends TestClient {
buildquery();
System.out.println(query);
setStatusString("Congratulations, your certificate has been issued.");
- return (Send());
+ return(Send());
} catch (Exception e) {
System.err.println("some exception:" + e);
}
@@ -162,11 +157,10 @@ public class DirEnroll extends TestClient {
}
/**
- * Enroll for certificate . Before calling this mentod SetAuthenticator and
- * setUIDInfo
+ * Enroll for certificate . Before calling this mentod SetAuthenticator and setUIDInfo
*/
public boolean enroll() {
- return (pkcs10());
+ return(pkcs10());
}
private boolean readProperties() {
@@ -175,8 +169,8 @@ public class DirEnroll extends TestClient {
try {
getProperties(propfileName);
} catch (Exception e) {
- System.out.println("exception reading Properties File "
- + e.getMessage());
+ System.out.println(
+ "exception reading Properties File " + e.getMessage());
return false;
}
@@ -218,7 +212,7 @@ public class DirEnroll extends TestClient {
return true;
}
- // Private functions
+ // Private functions
private boolean importCert(String certpack) {
@@ -232,8 +226,8 @@ public class DirEnroll extends TestClient {
}
if (debug) {
- System.out.println("importing cert" + certpack + "certnick"
- + certnickname);
+ System.out.println(
+ "importing cert" + certpack + "certnick" + certnickname);
}
cCrypt.importCert(certpack, certnickname);
@@ -295,8 +289,8 @@ public class DirEnroll extends TestClient {
ps.println("\r");
ps.flush();
os.flush();
- BufferedReader stdin = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ BufferedReader stdin = new BufferedReader(
+ new InputStreamReader(socket.getInputStream()));
if (debug) {
System.out.println("Step 4: Received the page");
@@ -316,7 +310,7 @@ public class DirEnroll extends TestClient {
}
if (line.indexOf("record.base64Cert=") > -1) {
- String baseCert = line;
+ String baseCert = line;
System.out.println("BaseCert : " + baseCert);
if (importcert.equals("true")) {
@@ -325,8 +319,7 @@ public class DirEnroll extends TestClient {
int n = strbase.length() + 1;
baseCert = baseCert.substring(n);
- String tmp = baseCert.substring(0,
- baseCert.length() - 2);
+ String tmp = baseCert.substring(0, baseCert.length() - 2);
if (importCert(tmp)) {
impStatus = true;
@@ -359,13 +352,13 @@ public class DirEnroll extends TestClient {
}
return st;
-
+
}
private void buildquery() {
StringBuffer queryStrBuf = new StringBuffer();
-
+
queryStrBuf.append("certType=client");
queryStrBuf.append("&importCert=off");
queryStrBuf.append("&non_repudiation=true");
@@ -383,7 +376,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append(URLEncoder.encode(UID));
queryStrBuf.append("&pwd=");
queryStrBuf.append(URLEncoder.encode(PWD));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
queryStrBuf.append("&cryptprovider=1");
}
@@ -419,7 +412,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append("&l=");
queryStrBuf.append(URLEncoder.encode(L));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
}
@@ -430,7 +423,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append(URLEncoder.encode(UID));
queryStrBuf.append("&pwd=");
queryStrBuf.append(URLEncoder.encode(PWD));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
}
@@ -439,36 +432,37 @@ public class DirEnroll extends TestClient {
query = queryStrBuf.toString();
System.out.println(query);
-
+
}
public static void main(String args[]) {
// Exit Status - (0) for error/Fail
// - requestId Pass
boolean st;
-
+
System.out.println(args.length);
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
DirEnroll t = new DirEnroll(args[0]);
t.readProperties();
st = t.enroll();
- if (st) {
- System.out.println(t.getAuthenticator()
- + " based enrollment successfull. ");
+ if (st) {
+ System.out.println(
+ t.getAuthenticator() + " based enrollment successfull. ");
System.exit(1);
} else {
- System.out.println(t.getAuthenticator()
- + " based enrollment was not successful." + "Error: "
- + t.getErrorDetail());
+ System.out.println(
+ t.getAuthenticator()
+ + " based enrollment was not successful."
+ + "Error: " + t.getErrorDetail());
System.exit(0);
}
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java b/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
index 36392fd1..79be5c35 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -32,6 +31,7 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
+
public class ParseXML {
Document dom = null;
@@ -53,8 +53,7 @@ public class ParseXML {
se.printStackTrace();
try {
- BufferedReader br = new BufferedReader(
- new InputStreamReader(is));
+ BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
@@ -78,7 +77,7 @@ public class ParseXML {
// get the root elememt
Element docEle = dom.getDocumentElement();
-
+
// get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName(tag);
@@ -108,10 +107,9 @@ public class ParseXML {
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(dom);
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
}
-
+
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
@@ -134,7 +132,7 @@ public class ParseXML {
try {
// get the root elememt
Element docEle = dom.getDocumentElement();
-
+
// get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName(first);
@@ -165,8 +163,10 @@ public class ParseXML {
px.parse(fiscfg);
px.prettyprintxml();
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
}
-}; // end class
+}
+
+
+; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java b/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
index 1e08efd3..87fcf500 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -30,11 +29,12 @@ import java.net.URL;
import com.netscape.osutil.OSUtil;
/**
- * CMS Test framework . This class submits request to admin server after
- * authenticating with UID and Password. You can get back the response by
- * calling the method. getPage().
+ * CMS Test framework .
+ * This class submits request to admin server after authenticating with UID and Password. You can get back the response by calling the method. getPage().
*/
+
+
public class PostQuery {
private boolean st;
@@ -45,14 +45,10 @@ public class PostQuery {
private StringBuffer stdout = new StringBuffer();
/**
- * Constructor . Takes the parameters
- * urlstring("http://hostname:<portnumber> , Id for authenticating to the
- * server, password for authentication to the server and query which needs
- * to be submitted to the server
+ * Constructor . Takes the parameters urlstring("http://hostname:<portnumber> , Id for authenticating to the server, password for authentication to the server and query which needs to be submitted to the server
*/
- public PostQuery(String urlstr, String authid, String authpwd,
- String querystring) {
+ public PostQuery(String urlstr, String authid, String authpwd, String querystring) {
URLString = urlstr;
adminID = authid;
@@ -79,24 +75,24 @@ public class PostQuery {
}
public boolean Send() {
- // / This functions connects to the URL and POST HTTP Request .
- // It compares with NMC_STATUS and return the status.
+ // / This functions connects to the URL and POST HTTP Request .
+ // It compares with NMC_STATUS and return the status.
System.out.println(URLString);
st = false;
try {
- BufferedReader mbufferedReader = null;
+ BufferedReader mbufferedReader = null;
URL myUrl = new URL(URLString);
String userPassword = adminID + ":" + adminPWD;
System.out.println("adminid=" + adminID);
System.out.println("adminpwd=" + adminPWD);
// String encoding = new sun.misc.BASE64Encoder().encode(
- // userPassword.getBytes());
- String encoding = OSUtil.BtoA(userPassword.getBytes());
- HttpURLConnection URLCon = (HttpURLConnection) myUrl
- .openConnection();
+ // userPassword.getBytes());
+ String encoding = OSUtil.BtoA(
+ userPassword.getBytes());
+ HttpURLConnection URLCon = (HttpURLConnection) myUrl.openConnection();
URLCon.setRequestProperty("Authorization", "Basic " + encoding);
URLCon.setDoOutput(true);
@@ -107,7 +103,7 @@ public class PostQuery {
// URLCon.setRequestMethod("POST");
System.out.println("After post");
- DataOutputStream os = new DataOutputStream(URLCon.getOutputStream());
+ DataOutputStream os = new DataOutputStream(URLCon.getOutputStream());
System.out.println("Query: " + postQuery);
@@ -116,12 +112,12 @@ public class PostQuery {
os.writeBytes(postQuery);
os.flush();
os.close();
-
+
InputStream Content = (InputStream) URLCon.getInputStream();
System.out.println("Configuring Cert Instance : Return Response");
- BufferedReader in = new BufferedReader(new InputStreamReader(
- Content));
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(Content));
String line;
while ((line = in.readLine()) != null) {
@@ -131,12 +127,12 @@ public class PostQuery {
if (st) {
break;
}
- }
+ }
URLCon.disconnect();
- } // try
+ } // try
catch (MalformedURLException e) {
System.out.println(URLString + " is not a valid URL.");
-
+
} catch (IOException e) {
System.out.println("exception : " + e.getMessage());
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Request.java b/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
index b8a476cf..9ddc9970 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,24 +17,28 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Vector;
+
+
/**
- * CMS Test framework . Submits List,Approve,Reject,cancel requests to agent
- * port
+ * CMS Test framework .
+ * Submits List,Approve,Reject,cancel requests to agent port
*/
+
public class Request extends TestClient {
private String validityperiod;
private String approveseqnum, type, reqType, reqState, agenttype;
private int i;
- // Program variables
+ // Program variables
private String ACTION_PROCESS_CERT_REQUEST = null;
private String ACTION_LISTREQUEST = "/queryReq";
private int reqtype = 1;
@@ -49,33 +52,29 @@ public class Request extends TestClient {
private Vector<String> seqNum = new Vector<String>();
private String AUTH_ID = null;
- // Cert Detail variables
+ // Cert Detail variables
- private String csrRequestorName, csrRequestorPhone, csrRequestorEmail,
- subject, subjectdn, reqStatus, certType;
- private String requestType, requestID, sslclient, clientcert, servercert,
- emailcert, objectsigningcert, sslcacert, objectsigningcacert,
- emailcacert, sigAlgo, totalRecord, validitylength, trustedManager;
+ private String csrRequestorName, csrRequestorPhone, csrRequestorEmail, subject, subjectdn, reqStatus, certType;
+ private String requestType, requestID, sslclient, clientcert, servercert, emailcert, objectsigningcert, sslcacert, objectsigningcacert, emailcacert, sigAlgo, totalRecord, validitylength, trustedManager;
private int totalNumApproved = 0;
- // Constructors
+ // Constructors
/**
* Constructor . Takes the parameter for Properties file name
- *
- * @param propfileName name of the parameter file.
+ * @param propfileName name of the parameter file.
*/
+
public Request(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter host , port and "angent type - ca/ra"
- *
+ * Constructor . Takes the parameter host , port and "angent type - ca/ra"
* @param hostname.
- * @param port
+ * @param port
* @param agenttype Whether ca or ra agent
*/
@@ -86,10 +85,9 @@ public class Request extends TestClient {
}
/**
- * Constructor . Takes the following parmaters
- *
- * @param hostName .
- * @param port
+ * Constructor . Takes the following parmaters
+ * @param hostName .
+ * @param port
* @param adminuid
* @param adminpwd
* @param agentcertnickname
@@ -99,15 +97,14 @@ public class Request extends TestClient {
* @param ApproveSequenceNumberFrom
* @param ApproveSequnceNumberTo
* @param type
- * @param reqtype enrollment/revoked
- * @param requestState complete/pending
- * @param agentType ra/ca
- * @param trustedManager true/false
+ * @param reqtype enrollment/revoked
+ * @param requestState complete/pending
+ * @param agentType ra/ca
+ * @param trustedManager true/false
*/
- public Request(String h, String p, String aid, String apwd, String cname,
- String cd, String ctpwd, String snum, String sfrom, String sto,
- String ty, String rty, String rstate, String aty, String tm) {
+
+ public Request(String h, String p, String aid, String apwd, String cname, String cd, String ctpwd, String snum, String sfrom, String sto, String ty, String rty, String rstate, String aty, String tm) {
host = h;
ports = p;
adminid = aid;
@@ -145,22 +142,19 @@ public class Request extends TestClient {
}
/**
- * Set Agent Cert nick name
+ * Set Agent Cert nick name
*/
public void setAgentCertName(String s) {
certnickname = s;
}
/**
- * List all pending enrollment request. Takes parameters
- * fromRequestNumber,toRequestNumber
- *
- * @param fromrequest number
+ * List all pending enrollment request. Takes parameters fromRequestNumber,toRequestNumber
+ * @param fromrequest number
* @param endrequestnumber.
*/
- public Vector<String> ListPendingRequests(String fromRequestNumber,
- String toRequestNumber) {
+ public Vector<String> ListPendingRequests(String fromRequestNumber, String toRequestNumber) {
reqState = "showWaiting";
reqType = "enrollment";
approveseqnumFrom = fromRequestNumber;
@@ -170,15 +164,13 @@ public class Request extends TestClient {
}
/**
- * List all pending request. Takes parameters
- * fromRequestNumber,toRequestNumber
- *
- * @param fromrequest number
+ * List all pending request. Takes parameters fromRequestNumber,toRequestNumber
+ * @param fromrequest number
* @param endrequestnumber.
*/
- public Vector<String> ListAllRequests(String fromRequestNumber,
- String toRequestNumber) {
+
+ public Vector<String> ListAllRequests(String fromRequestNumber, String toRequestNumber) {
reqState = "showAll";
reqType = "enrollment";
approveseqnumFrom = fromRequestNumber;
@@ -189,10 +181,10 @@ public class Request extends TestClient {
/**
* Approve pending enrollment request. Takes parameters RequestNumber
- *
- * @param request number
+ * @param request number
*/
+
public int ApproveRequests(String requestNumber) {
reqState = "showWaiting";
reqType = "enrollment";
@@ -209,10 +201,8 @@ public class Request extends TestClient {
}
/**
- * Approve profile based pending enrollment request. Takes parameters
- * RequestNumber
- *
- * @param request number
+ * Approve profile based pending enrollment request. Takes parameters RequestNumber
+ * @param request number
*/
public int ApproveProfileRequests(String RequestNumber) {
@@ -231,25 +221,23 @@ public class Request extends TestClient {
}
- public boolean Approve_cadualcert_Profile_Request(String RequestNumber,
- String name) {
-
+ public boolean Approve_cadualcert_Profile_Request(String RequestNumber, String name) {
+
approveseqnum = RequestNumber;
approveseqnumFrom = RequestNumber;
approveseqnumTo = RequestNumber;
cadualcert_name = name;
- // reqtype = 7 means cadualcert profile request
- // this is just a convention that we follow within this file to
- // distinguish
+ // reqtype = 7 means cadualcert profile request
+ // this is just a convention that we follow within this file to distinguish
// bet'n the different requests
reqtype = 7;
buildquery();
- if (!Send()) {
+ if (!Send()) {
System.out.println("Error: Approving request " + approveseqnum);
return false;
}
@@ -259,12 +247,11 @@ public class Request extends TestClient {
}
/**
- * Reject profile based pending enrollment request. Takes parameters
- * RequestNumber
- *
- * @param request number
+ * Reject profile based pending enrollment request. Takes parameters RequestNumber
+ * @param request number
*/
+
public int RejectProfileRequests(String RequestNumber) {
approveseqnum = RequestNumber;
@@ -282,10 +269,8 @@ public class Request extends TestClient {
}
/**
- * Cancel profile based pending enrollment request. Takes parameters
- * RequestNumber
- *
- * @param request number
+ * Cancel profile based pending enrollment request. Takes parameters RequestNumber
+ * @param request number
*/
public int CancelProfileRequests(String RequestNumber) {
@@ -304,7 +289,7 @@ public class Request extends TestClient {
}
- // private methods
+ // private methods
private boolean RetrieveProfileCancel(StringBuffer s) {
String res = s.toString();
int ret = 0;
@@ -369,21 +354,20 @@ public class Request extends TestClient {
AUTH_ID = res.substring(ret + AUTHID.length() + 1,
res.indexOf(";", ret) - 1);
while (ret > 0) {
- if ((ret = res.indexOf(seqnum, ret)) > -1) {
- int bi = ret + seqnum.length() + 2;
+ if ((ret = res.indexOf(seqnum, ret)) > -1) {
+ int bi = ret + seqnum.length() + 2;
int be = res.indexOf(";", ret) - 1;
seqNum.addElement(res.substring(bi, be));
ret++;
- }
-
+ }
+
}
}
ret = res.indexOf("header.totalRecordCount =");
- totalRecord = res.substring(
- ret + "header.totalRecordCount = ".length(),
+ totalRecord = res.substring(ret + "header.totalRecordCount = ".length(),
res.indexOf(";", ret));
return true;
@@ -406,26 +390,26 @@ public class Request extends TestClient {
String cmp = "header.SERVER_ATTRS[" + t + "].name=";
ret = res.indexOf(cmp);
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("requestId")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "requestId")) {
ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value=");
requestID = res.substring(
ret + "header.SERVER_ATTRS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("requestStatus")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "requestStatus")) {
ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value=");
reqStatus = res.substring(
ret + "header.SERVER_ATTRS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("requestType")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "requestType")) {
ret = res.indexOf("header.SERVER_ATTRS[" + t + "].value=");
- requestType = res.substring(ret
- + "header.SERVER_ATTRS[t].value=".length() + 1,
+ requestType = res.substring(
+ ret + "header.SERVER_ATTRS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
@@ -438,8 +422,7 @@ public class Request extends TestClient {
}
if (!st) {
- System.out.println("Error in retrieving the record "
- + approveseqnum);
+ System.out.println("Error in retrieving the record " + approveseqnum);
return false;
}
@@ -449,39 +432,39 @@ public class Request extends TestClient {
String cmp = "header.HTTP_PARAMS[" + t + "].name=";
ret = res.indexOf(cmp);
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("csrRequestorEmail")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "csrRequestorEmail")) {
ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value=");
- csrRequestorEmail = res.substring(ret
- + "header.HTTP_PARAMS[t].value=".length() + 1,
+ csrRequestorEmail = res.substring(
+ ret + "header.HTTP_PARAMS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("csrRequestorPhone")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "csrRequestorPhone")) {
ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value=");
- csrRequestorPhone = res.substring(ret
- + "header.HTTP_PARAMS[t].value=".length() + 1,
+ csrRequestorPhone = res.substring(
+ ret + "header.HTTP_PARAMS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("csrRequestorName")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "csrRequestorName")) {
ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value=");
- csrRequestorName = res.substring(ret
- + "header.HTTP_PARAMS[t].value=".length() + 1,
+ csrRequestorName = res.substring(
+ ret + "header.HTTP_PARAMS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("subject")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "subject")) {
ret = res.indexOf("header.HTTP_PARAMS[" + t + "].value=");
subjectdn = res.substring(
ret + "header.HTTP_PARAMS[t].value=".length() + 1,
res.indexOf(";", ret) - 1);
}
- } // end of for loop
+ } // end of for loop
- // System.out.println("Debug : Retrieving cert details");
+ // System.out.println("Debug : Retrieving cert details");
ret = res.indexOf("header.subject =");
if (ret > 0) {
@@ -498,6 +481,7 @@ public class Request extends TestClient {
}
// System.out.println("Debug : Retrieving cert details ");
+
ret = res.indexOf("header.ext_ssl_client =");
if (ret > 0) {
clientcert = res.substring(
@@ -524,8 +508,8 @@ public class Request extends TestClient {
ret = res.indexOf("header.ext_object_signing =");
if (ret > 0) {
- objectsigningcert = res.substring(ret
- + "header.ext_object_signing = ".length() + 1,
+ objectsigningcert = res.substring(
+ ret + "header.ext_object_signing = ".length() + 1,
res.indexOf(";", ret) - 1);
}
@@ -533,8 +517,7 @@ public class Request extends TestClient {
ret = res.indexOf("header.ext_ssl_ca =");
if (ret > 0) {
- sslcacert = res.substring(
- ret + "header.ext_ssl_ca = ".length() + 1,
+ sslcacert = res.substring(ret + "header.ext_ssl_ca = ".length() + 1,
res.indexOf(";", ret) - 1);
}
@@ -543,16 +526,17 @@ public class Request extends TestClient {
if (ret > 0) {
ret = res.indexOf("header.ext_object_signing_ca=");
}
- objectsigningcacert = res.substring(ret
- + "header.ext_object_signing_ca = ".length() + 1,
+ objectsigningcacert = res.substring(
+ ret + "header.ext_object_signing_ca = ".length() + 1,
res.indexOf(";", ret) - 1);
// System.out.println("Debug : Retrieving cert details ");
ret = res.indexOf("header.ext_email_ca =");
if (ret > 0) {
- emailcacert = res.substring(ret + "header.ext_email_ca = ".length()
- + 1, res.indexOf(";", ret) - 1);
+ emailcacert = res.substring(
+ ret + "header.ext_email_ca = ".length() + 1,
+ res.indexOf(";", ret) - 1);
}
// System.out.println("Debug : Retrieving cert details ");
@@ -590,7 +574,7 @@ public class Request extends TestClient {
System.out.println(res);
}
- // Find th Server_ATTRS paramteter value of reqStatus
+ // Find th Server_ATTRS paramteter value of reqStatus
int i = 1;
int ret;
@@ -599,21 +583,21 @@ public class Request extends TestClient {
String cmp = "header.SERVER_ATTRS[" + t + "].name=";
ret = res.indexOf(cmp);
- if ((res.substring(ret + cmp.length() + 1,
- res.indexOf(";", ret) - 1)).equals("requestStatus")) {
+ if ((res.substring(ret + cmp.length() + 1, res.indexOf(";", ret) - 1)).equals(
+ "requestStatus")) {
i = t;
break;
- }
+ }
}
-
+
String req = "header.SERVER_ATTRS[" + i + "].value=";
ret = res.indexOf(req);
reqStatus = res.substring(ret + req.length() + 1,
res.indexOf(";", ret) - 1);
- if (reqStatus != null) {
+ if (reqStatus != null) {
reqStatus.toLowerCase();
if (reqStatus.equals("complete")) {
return true;
@@ -643,7 +627,7 @@ public class Request extends TestClient {
con.setQueryString(query);
con.setActionURL(ACTION_STRING);
con.Send();
- StringBuffer s = new StringBuffer();
+ StringBuffer s = new StringBuffer();
s = con.getPage();
String line;
@@ -661,7 +645,7 @@ public class Request extends TestClient {
break;
case 3:
- st = approveRequestStatus(s);
+ st = approveRequestStatus(s);
break;
case 4:
@@ -681,7 +665,7 @@ public class Request extends TestClient {
break;
default:
- System.out.println("reqtype not recognized");
+ System.out.println("reqtype not recognized");
}
} catch (Exception e) {
System.err.println("exception: in Send routine" + e);
@@ -701,7 +685,7 @@ public class Request extends TestClient {
query += "&reqState=" + reqState;
}
-
+
if (reqtype == 2) { // get cert details
ACTION_PROCESS_CERT_REQUEST = "/" + AUTH_ID + "/processCertReq";
ACTION_STRING = ACTION_PROCESS_CERT_REQUEST;
@@ -715,7 +699,7 @@ public class Request extends TestClient {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -735,7 +719,7 @@ public class Request extends TestClient {
if (csrRequestorPhone != null) {
query += "&csrRequestorPhone=" + csrRequestorPhone;
}
-
+
if (csrRequestorEmail != null) {
query += "&csrRequestorEmail=" + csrRequestorEmail;
}
@@ -762,7 +746,7 @@ public class Request extends TestClient {
query += "&certTypeSSLServer=" + servercert;
}
- if (emailcert.equals("true")) {
+ if (emailcert.equals("true")) {
query += "&certTypeEmail=" + emailcert;
}
@@ -774,15 +758,13 @@ public class Request extends TestClient {
}
- if ((reqtype == 4) || (reqtype == 5) || (reqtype == 6)) { // profile
- // based cert
- // request
+ if ((reqtype == 4) || (reqtype == 5) || (reqtype == 6)) { // profile based cert request
if (validityperiod != null) {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -790,8 +772,8 @@ public class Request extends TestClient {
ACTION_STRING = ACTION_PROCESS_CERT_REQUEST;
query = "requestId=" + approveseqnum;
query += "&name="
- + URLEncoder
- .encode("UID=test,E=test,CN=test,OU=netscape,O=aol");
+ + URLEncoder.encode(
+ "UID=test,E=test,CN=test,OU=netscape,O=aol");
query += "&keyUsageCritical=true";
query += "&keyUsageDigitalSignature=true";
query += "&keyUsageNonRepudiation=true";
@@ -827,9 +809,9 @@ public class Request extends TestClient {
// Date begindate = begin.getTime();
// Date enddate = end.getTime();
String nb = begin.get(Calendar.YEAR) + "-"
- + begin.get(Calendar.MONTH) + "-"
- + begin.get(Calendar.DATE) + " " + begin.get(Calendar.HOUR)
- + ":" + begin.get(Calendar.MINUTE) + ":"
+ + begin.get(Calendar.MONTH) + "-" + begin.get(Calendar.DATE)
+ + " " + begin.get(Calendar.HOUR) + ":"
+ + begin.get(Calendar.MINUTE) + ":"
+ begin.get(Calendar.SECOND);
String nat = end.get(Calendar.YEAR) + "-" + end.get(Calendar.MONTH)
@@ -868,9 +850,9 @@ public class Request extends TestClient {
end.add(GregorianCalendar.DATE, validperiod);
String nb = begin.get(Calendar.YEAR) + "-"
- + begin.get(Calendar.MONTH) + "-"
- + begin.get(Calendar.DATE) + " " + begin.get(Calendar.HOUR)
- + ":" + begin.get(Calendar.MINUTE) + ":"
+ + begin.get(Calendar.MONTH) + "-" + begin.get(Calendar.DATE)
+ + " " + begin.get(Calendar.HOUR) + ":"
+ + begin.get(Calendar.MINUTE) + ":"
+ begin.get(Calendar.SECOND);
String nat = end.get(Calendar.YEAR) + "-" + end.get(Calendar.MONTH)
@@ -880,30 +862,28 @@ public class Request extends TestClient {
query = "requestId=" + approveseqnum + "&name="
+ URLEncoder.encode(cadualcert_name) + "&notBefore=" + nb
- + "&notAfter="
- + nat
- + "&authInfoAccessCritical=false"
- + "&authInfoAccessGeneralNames="
- + "&keyUsageCritical=true"
+ + "&notAfter=" + nat + "&authInfoAccessCritical=false"
+ + "&authInfoAccessGeneralNames=" + "&keyUsageCritical=true"
+ "&keyUsageDigitalSignature=false"
+ "&keyUsageNonRepudiation=false"
+ "&keyUsageKeyEncipherment=true"
+ "&keyUsageDataEncipherment=false"
+ "&keyUsageKeyAgreement=false"
- + "&keyUsageKeyCertSign=false"
- + "&keyUsageCrlSign=false"
+ + "&keyUsageKeyCertSign=false" + "&keyUsageCrlSign=false"
+ "&keyUsageEncipherOnly=false"
- + "&keyUsageDecipherOnly=false"
- + /*
- * -- For Older CMS 6.x servers use these
- * "&nsCertCritical=false" + "&nsCertSSLClient=true" +
- * "&nsCertSSLServer=false" + "&nsCertEmail=true" +
- * "&nsCertObjectSigning=false" + "&nsCertSSLCA=false" +
- * "&nsCertEmailCA=false" + "&nsCertObjectSigningCA=false"
- * + "&subjAltNameExtCritical=false" +
- * "&subjAltNames=RFC822Name: null" +
- * "&signingAlg=MD5withRSA" +
- */// For newer CS 7.x servers use these
+ + "&keyUsageDecipherOnly=false" + /* -- For Older CMS 6.x servers use these
+ "&nsCertCritical=false" +
+ "&nsCertSSLClient=true" +
+ "&nsCertSSLServer=false" +
+ "&nsCertEmail=true" +
+ "&nsCertObjectSigning=false" +
+ "&nsCertSSLCA=false" +
+ "&nsCertEmailCA=false" +
+ "&nsCertObjectSigningCA=false" +
+ "&subjAltNameExtCritical=false" +
+ "&subjAltNames=RFC822Name: null" +
+ "&signingAlg=MD5withRSA" +
+ */ // For newer CS 7.x servers use these
"&exKeyUsageCritical=false"
+ "&exKeyUsageOIDs=1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.4"
+ "&subjAltNameExtCritical=false"
@@ -912,7 +892,7 @@ public class Request extends TestClient {
+ "&op=approve" + "&submit=submit";
}
-
+
}
private void readProperties() {
@@ -921,8 +901,8 @@ public class Request extends TestClient {
try {
getProperties(propfileName);
} catch (Exception e) {
- System.out.println("exception reading Properties File "
- + e.getMessage());
+ System.out.println(
+ "exception reading Properties File " + e.getMessage());
}
// Read the properties file
@@ -988,14 +968,14 @@ public class Request extends TestClient {
maxCount = 50;
} else {
maxCount = y.intValue() - x.intValue();
- }
+ }
if (maxCount == 0) {
maxCount = 1;
- }
+ }
reqtype = 1;
buildquery();
- return (Send());
+ return(Send());
}
private boolean approveRequest() {
@@ -1009,20 +989,20 @@ public class Request extends TestClient {
return false;
}
- if (approveseqnum.length() > 0) {
+ if (approveseqnum.length() > 0) {
if (seqNum.contains(approveseqnum)) {
seqNum.removeAllElements();
seqNum.addElement(approveseqnum);
} else {
- System.out.println(" Seq num " + approveseqnum
- + " already approved ");
+ System.out.println(
+ " Seq num " + approveseqnum + " already approved ");
return false;
}
} else {
- System.out
- .println(" Seq num not specified . Approving all pending request From : "
+ System.out.println(
+ " Seq num not specified . Approving all pending request From : "
+ approveseqnumFrom + " To : " + approveseqnumTo);
- }
+ }
boolean flag = true;
@@ -1035,7 +1015,7 @@ public class Request extends TestClient {
while (i < seqNum.size()) {
approveseqnum = (seqNum.elementAt(i)).toString();
- // Get request details
+ // Get request details
reqtype = 2;
buildquery();
if (!Send()) {
@@ -1043,43 +1023,44 @@ public class Request extends TestClient {
i++;
continue;
}
-
+
if (debug) {
- System.out.println(csrRequestorName + " "
- + csrRequestorPhone + " " + csrRequestorEmail + " "
- + requestID + " " + subject);
+ System.out.println(
+ csrRequestorName + " " + csrRequestorPhone + " "
+ + csrRequestorEmail + " " + requestID + " "
+ + subject);
}
- // Now for pending status - approve the request
+ // Now for pending status - approve the request
reqtype = 3;
buildquery();
if (!Send()) {
- System.out.println("Error: Approving request "
- + approveseqnum);
+ System.out.println(
+ "Error: Approving request " + approveseqnum);
i++;
continue;
}
- System.out
- .println("Request " + approveseqnum + " is approved ");
+ System.out.println("Request " + approveseqnum + " is approved ");
totalNumApproved++;
- i++;
+ i++;
}
Integer x = new Integer(approveseqnum);
- if (x.intValue() >= torequest) {
+ if (x.intValue() >= torequest) {
flag = false;
- } else {
+ } else {
listRequest(approveseqnum, approveseqnumTo);
}
-
+
}
return st;
}
/**
- * Use this method when you need to use properties file.
+ * Use this method when you need to use properties file.
*/
- public int processRequest() {
+
+ public int processRequest() {
if (propfileName != null) {
readProperties();
}
@@ -1109,7 +1090,7 @@ public class Request extends TestClient {
} else {
return 0;
}
- } else {
+ } else {
return -1;
}
@@ -1122,11 +1103,11 @@ public class Request extends TestClient {
// Exit Status - (0) for error
// - any number > 0 Pass
int st = 0;
-
+
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
Request t = new Request(args[0]);
@@ -1139,5 +1120,5 @@ public class Request extends TestClient {
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java b/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
index 363e6741..89fa768c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -24,36 +23,32 @@ import java.io.FileReader;
import java.net.InetAddress;
import java.util.StringTokenizer;
+
/**
- * CMS Test framework . This class fetches all the necssary ServerInformation to
- * run the test . For example AdminServer information linke port , hsotname,
- * Config LDAP server port, CMS servers Agentport,AdminPort, EESSL port, EE port
- * etc..
+ * CMS Test framework .
+ * This class fetches all the necssary ServerInformation to run the test . For example AdminServer information linke port , hsotname, Config LDAP server port, CMS servers Agentport,AdminPort, EESSL port, EE port etc..
*/
+
public class ServerInfo {
public String serverRoot, instanceRoot, instanceID;
- public String ldapPort, ldapHost, ldapSSLPort, ldapBaseSuffix, adminPort,
- admDN, admDNPW, singleSignOnPWD, domain;
- public String caSigningCertNickName, raSigningCertNickName,
- ocspSigningCertNickName, kraTransportCertNickName;
+ public String ldapPort, ldapHost, ldapSSLPort, ldapBaseSuffix, adminPort, admDN, admDNPW, singleSignOnPWD, domain;
+ public String caSigningCertNickName, raSigningCertNickName, ocspSigningCertNickName, kraTransportCertNickName;
public String ServerCertNickName, CertAuthority;
public String CMSAgentPort, CMSEESSLPort, CMSEEPort, CMSAdminPort, IDBPort;
public static CMSProperties props = null;
public static CMSProperties CMSprops = null;
- // Private variables
+ // Private variables
private int i;
public String CMSConfigFile, AdminConfigFile;
- public ServerInfo() {
- }
+ public ServerInfo() {}
/**
- * Constructor. Takes Server root as parameter for example ( /export/qa).
- * Reads and collects information about adminserver and Config LDAP server.
+ * Constructor. Takes Server root as parameter for example ( /export/qa). Reads and collects information about adminserver and Config LDAP server.
*/
public ServerInfo(String sroot) {
serverRoot = sroot;
@@ -63,11 +58,10 @@ public class ServerInfo {
}
/**
- * Constructor. Takes Serverroot ( /export/qa) and instanceRoot
- * (/export/qa/cert-jupiter2) as parameters . Reads and collects information
- * about Admin Server , Config LDAP server and CMS server .
+ * Constructor. Takes Serverroot ( /export/qa) and instanceRoot (/export/qa/cert-jupiter2) as parameters . Reads and collects information about Admin Server , Config LDAP server and CMS server .
*/
+
public ServerInfo(String sroot, String instRoot) {
serverRoot = sroot;
instanceRoot = instRoot;
@@ -88,10 +82,10 @@ public class ServerInfo {
return ldapPort;
}
- public String GetHostName() {
+ public String GetHostName() {
if (domain.indexOf(".") > 0) {
return domain.substring(0, domain.indexOf("."));
- } else {
+ } else {
return domain;
}
}
@@ -104,8 +98,8 @@ public class ServerInfo {
return CMSConfigFile;
}
- public String GetDomainName() {
- return ldapHost.substring(ldapHost.indexOf(".") + 1);
+ public String GetDomainName() {
+ return ldapHost.substring(ldapHost.indexOf(".") + 1);
}
public String GetAgentPort() {
@@ -154,15 +148,15 @@ public class ServerInfo {
readCMSConfig();
}
- // Private functions
+ // Private functions
private void SystemInfo() {
try {
- domain = InetAddress.getLocalHost().getHostName();
+ domain = InetAddress.getLocalHost().getHostName();
System.out.println("Debu:SystemInfo " + domain);
} catch (Exception e) {
System.out.println("Exception InetAddress : " + e.getMessage());
}
-
+
}
private void parseServerXML() {
@@ -171,7 +165,7 @@ public class ServerInfo {
int EE_SSL = 3;
int EE_NON_SSL = 4;
int IP = 5;
- int PORT = 6;
+ int PORT = 6;
BufferedReader in = null;
try {
@@ -215,12 +209,11 @@ public class ServerInfo {
} else if (token.equals(" port=")) {
index2 = PORT;
}
-
- if (index1 != 5 && index2 == IP
- && !token.equals(" ip=")) {
+
+ if (index1 != 5 && index2 == IP && !token.equals(" ip=")) {
String ip = token;
} else if (index2 == PORT && !token.equals(" port=")) {
-
+
switch (index1) {
case 1:
CMSAgentPort = token;
@@ -239,7 +232,7 @@ public class ServerInfo {
break;
default:
- break;
+ break;
}
@@ -254,11 +247,10 @@ public class ServerInfo {
if (in != null) {
try {
in.close();
- } catch (Exception ex) {
- }
+ } catch (Exception ex) {}
}
}
- }
+ }
private void getProperties(String filePath) throws Exception {
try {
@@ -282,7 +274,7 @@ public class ServerInfo {
if ((s.charAt(i) == ' ')) {
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -302,7 +294,7 @@ public class ServerInfo {
if (fis.read(b) != b.length) {
System.out.println("Could not read ");
- } else {
+ } else {
String tmpstr = new String(b, 0, b.length);
int ret;
@@ -320,14 +312,14 @@ public class ServerInfo {
// System.out.println(ldapPort);
}
if ((ret = tmpstr.indexOf(adminPortStr)) > -1) {
- adminPort = tmpstr.substring(ret + adminPortStr.length()
- + 1, tmpstr.indexOf("ldapStart", ret) - 1);
+ adminPort = tmpstr.substring(ret + adminPortStr.length() + 1,
+ tmpstr.indexOf("ldapStart", ret) - 1);
adminPort = stripSpace(adminPort);
// System.out.println(adminPort);
}
}
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -345,17 +337,17 @@ public class ServerInfo {
System.out.println("Reading CMS Config file successful");
CertAuthority = CMSprops.getProperty("subsystem.0.id");
if (CertAuthority.equals("ca")) {
- caSigningCertNickName = CMSprops
- .getProperty("ca.signing.cacertnickname");
+ caSigningCertNickName = CMSprops.getProperty(
+ "ca.signing.cacertnickname");
ServerCertNickName = "Server-Cert cert-" + instanceID;
}
if (CertAuthority.equals("ra")) {
- raSigningCertNickName = CMSprops
- .getProperty("ra.signing.cacertnickname");
+ raSigningCertNickName = CMSprops.getProperty(
+ "ra.signing.cacertnickname");
ServerCertNickName = "Server-Cert cert-" + instanceID;
}
IDBPort = CMSprops.getProperty("internaldb.ldapconn.port");
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -369,18 +361,18 @@ public class ServerInfo {
System.out.println(" Admin Port : " + s.GetAdminPort());
System.out.println(" LDAP Port : " + s.GetConfigLDAPPort());
System.out.println("Hostname " + s.GetHostName());
- System.out.println("InstanceID" + s.GetInstanceID());
- System.out.println(" doamin name : " + s.GetDomainName());
+ System.out.println("InstanceID" + s.GetInstanceID());
+ System.out.println(" doamin name : " + s.GetDomainName());
System.out.println("AgentPort " + s.GetAgentPort());
System.out.println("EESSLPort " + s.GetEESSLPort());
System.out.println("EEPort " + s.GetEEPort());
- System.out.println("CMSAdminPort :" + s.GetCMSAdminPort());
+ System.out.println("CMSAdminPort :" + s.GetCMSAdminPort());
System.out.println("CAAuthority : " + s.GetCertAuthority());
System.out.println("CASigningCert:" + s.GetCASigningCert());
System.out.println("RASigningCert:" + s.GetRASigningCert());
System.out.println("ServerCert" + s.GetServerCertNickName());
-
+
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java b/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
index 52885c37..fc266856 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -29,11 +28,15 @@ import java.util.Properties;
import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.ssl.SSLCertificateApprovalCallback;
+
+
/**
- * CMS Test framework . Before createing an instance of this class make sure you
- * havae set an environment variable TEST_CONFIG_FILE.
+ * CMS Test framework .
+ * Before createing an instance of this class make sure you havae set an environment variable TEST_CONFIG_FILE.
*/
+
+
public class TestClient implements SSLCertificateApprovalCallback {
public int port;
@@ -41,8 +44,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
// properties file parameters
public static String host, ports, adminid, adminpwd, propfileName, cdir;
public static String certnickname, keysize, keytype, tokenpwd;
- public static String serverRoot, instanceRoot, ldaprootDN, ldaprootDNPW,
- caInstanceRoot, dataDirectory;
+ public static String serverRoot, instanceRoot, ldaprootDN, ldaprootDNPW, caInstanceRoot, dataDirectory;
// Program variables
public String STATUS;
@@ -50,20 +52,20 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String ACTION_STRING;
public String query;
public boolean debug = false;
- // Certificate nicknames to be used by Test Clients
+ // Certificate nicknames to be used by Test Clients
private int i;
private String testConfigFile;
- public String caAgentCertName = "ca-agent";
- public String raAgentCertName = "ra-agent";
- public String ocspAgentCertName = "ocsp-agent";
- public String kraAgentCertName = "kra-agent";
- public String tksAgentCertName = "tks-agent";
- public String singleSignOnPWD = "secret12";
+ public String caAgentCertName = "ca-agent";
+ public String raAgentCertName = "ra-agent";
+ public String ocspAgentCertName = "ocsp-agent";
+ public String kraAgentCertName = "kra-agent";
+ public String tksAgentCertName = "tks-agent";
+ public String singleSignOnPWD = "secret12";
public String adminCertName = "cn=admin";
private String ldapBaseSuffix = "dc=netscape,dc=com";
- private String admDN = "admin";
- private String admDNPW = "admin";
+ private String admDN = "admin";
+ private String admDNPW = "admin";
private String TmpDir;
private String TestLogFile;
private String startupTests, cleanupTests;
@@ -74,7 +76,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String UID, OU, O, DN, E, CN, C, GN, SN, L, MAIL;
// Enroll
protected String PWD;
- // CRypto
+ // CRypto
public ComCrypto cCrypt = new ComCrypto();
public String pkcs10request = null;
@@ -82,18 +84,19 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String ErrorDetail;
- private String serverKeyType, serverKeySize, serverKeyAlgo;
+ private String serverKeyType, serverKeySize, serverKeyAlgo;
- private String unauth[] = { "Unauthorized Access", "Server Error",
- "Not Found", "Generic Unauthorized" };
+ private String unauth[] = {
+ "Unauthorized Access", "Server Error",
+ "Not Found", "Generic Unauthorized"};
- public boolean approve(X509Certificate x509,
- SSLCertificateApprovalCallback.ValidityStatus status) {
+ public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) {
SSLServerCert = x509;
return true;
}
- // Constructor
+ // Constructor
+
public TestClient() {
keysize = "1024";
@@ -101,16 +104,15 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Constructor . Takes the parameter for keysize and keytype . Before
- * creating a new instance of this class make sure you have set
- * TEST_CONFIG_FILE variable in your environnemt. Reads the TEST_CONFIG_FILE
- * . Initializes the certificate database. See engage.cfg file for example.
- *
+ * Constructor . Takes the parameter for keysize and keytype .
+ * Before creating a new instance of this class make sure you have set TEST_CONFIG_FILE variable in your environnemt.
+ * Reads the TEST_CONFIG_FILE . Initializes the certificate database. See engage.cfg file for example.
* @param keysize
- * @param keytype
+ * @param keytype
*/
- public TestClient(String ks, String kt) {
+
+ public TestClient(String ks, String kt) {
testConfigFile = ReadEnv("TEST_CONFIG_FILE");
@@ -147,8 +149,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Imports certificate to cert database.Takes parameters Certpackage and
- * certnickname
+ * Imports certificate to cert database.Takes parameters Certpackage and certnickname
*/
boolean importCert(String cp, String nickname) {
@@ -176,6 +177,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
* This function returns true if you choose to executeCleanupTests
*/
+
public boolean executeCleanupTests() {
if (cleanupTests == null) {
@@ -214,7 +216,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String GetLDAPDNPW() {
return ldaprootDNPW;
- }
+ }
public String GetLDAPBASE() {
return ldapBaseSuffix;
@@ -298,10 +300,10 @@ public class TestClient implements SSLCertificateApprovalCallback {
public void setTestLogFile(String s) {
TestLogFile = s;
- }
+ }
/**
- * parses a http page and returns true if any error is returned by server
+ * parses a http page and returns true if any error is returned by server
**/
public boolean getError(String line) {
@@ -311,14 +313,14 @@ public class TestClient implements SSLCertificateApprovalCallback {
ret = line.indexOf("fixed.errorDetails");
if (line.indexOf("fixed.errorDetails") == 0) {
- ErrorDetail = line.substring(ret
- + ("fixed.errorDetails = ").length());
+ ErrorDetail = line.substring(
+ ret + ("fixed.errorDetails = ").length());
return true;
}
if (line.indexOf("fixed.errorDetails") >= 0) {
- ErrorDetail = line.substring(ret
- + ("fixed.errorDetails = ").length());
+ ErrorDetail = line.substring(
+ ret + ("fixed.errorDetails = ").length());
return true;
}
@@ -326,8 +328,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
if (line.indexOf("fixed.unexpectedError") == 0) {
System.out.println("Processing unexpectedError");
- ErrorDetail = line.substring(ret
- + ("fixed.unexpectedError = ").length());
+ ErrorDetail = line.substring(
+ ret + ("fixed.unexpectedError = ").length());
return true;
}
@@ -352,7 +354,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
ErrorDetail = line.substring(ret + ("errorReason=").length());
return true;
}
-
+
return false;
}
@@ -372,7 +374,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
- public String ReadEnv(String str) {
+ public String ReadEnv(String str) {
try {
Process p = null;
Runtime r = Runtime.getRuntime();
@@ -384,8 +386,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
p = r.exec("env");
}
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
@@ -409,8 +411,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
try {
getProperties(testConfigFile);
} catch (Exception e) {
- System.out.println("exception reading TestConfigFile "
- + e.getMessage());
+ System.out.println(
+ "exception reading TestConfigFile " + e.getMessage());
}
serverRoot = props.getProperty("SROOT");
@@ -424,7 +426,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
ldaprootDN = props.getProperty("LDAPROOTDN");
- // Strip of th e quotes "cn=directory manager" string
+ // Strip of th e quotes "cn=directory manager" string
if (ldaprootDN.indexOf("\"") > -1) {
ldaprootDN = ldaprootDN.substring(1, ldaprootDN.length() - 1);
}
@@ -481,8 +483,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * returns FreePort in this machine . Takes a parmater portnumber. For
- * example getFreePort("4026").
+ * returns FreePort in this machine . Takes a parmater portnumber. For example getFreePort("4026").
*/
public String getFreePort(String s) {
Integer x = new Integer(s);
@@ -505,7 +506,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
return (getString(p));
}
- // This following method doesn't Always get a free port.
+ // This following method doesn't Always get a free port.
// while (st) {
// if(isSocketUnused(host,p) )
// st=false;
@@ -516,7 +517,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
/**
- * Reads a file and returns the cert request as string
+ * Reads a file and returns the cert request as string
**/
public String readRequest(String filename) {
@@ -543,70 +544,73 @@ public class TestClient implements SSLCertificateApprovalCallback {
TestClient t = new TestClient("1024", "RSA");
/*
- * ******************************************************************
- * Sample programs to initialze calsses
- * ******************************************************************
+ *******************************************************************
+ * Sample programs to initialze calsses
+ *******************************************************************
*/
+
/*
- * *******************************************************************
- * To Test AutoInstaller
- * ******************************************************************
+ ********************************************************************
+ * To Test AutoInstaller
+ *******************************************************************
*/
+
/*
- * AutoInstaller a = new AutoInstaller(t.GetServerRoot());
- *
- * ServerInfo s = new ServerInfo(t.GetServerRoot()); System.out.println
- * (" Admin Port : " + s.GetAdminPort()); System.out.println
- * (" LDAP Port : "+ s.GetConfigLDAPPort()); System.out.println(
- * "Hostname " + s.GetHostName()); System.out.println(" doamin name : "
- * + s.GetDomainName());
- *
- * t.setHostName(s.GetHostName()); // Set adminServer Info
- * a.setAdminInfo
- * (s.GetHostName(),s.GetAdminPort(),s.GetDomainName(),"admin","admin");
- * a
- * .setAdminInfo(s.GetHostName(),s.GetAdminPort(),"mcom.com","admin","admin"
- * );
- *
- * // setCAInfo
- * a.setCAInfo(s.GetHostName(),"1027","8100","admin","secret12");
- * //setInternalDB info String dp = t.getFreePort("38900");
- * a.setInternalDBInfo
- * (s.GetHostName(),"38907","ca-db","cn=directory manager","secret12" );
- *
- * // set tokenInfo
- *
- * a.setTokenInfo("Internal","secret12");
- *
- * // set Subsystem info String agp = t.getFreePort("8100"); String adp
- * = t.getFreePort("8200"); String eesp = t.getFreePort("1027"); String
- * eep = t.getFreePort("1100");
- *
- * System.out.println(agp);
- *
- * a.setSubSystemInfo("testra",t.GetServerRoot(),"RSA","1024","MD5","365"
- * ,"cn=certificate manager,ou=test,o=test",adp,agp,eesp,eep);
- *
- * a.setClientDBInfo(t.GetClientCertDB(),"secret12",t.GetAdminCertName())
- * ;
- *
- * a.ConfigureCA("admin","admin","secret12","secret12");
- *
- * // a.ConfigureRA("admin","admin","secret12","secret12");
+ AutoInstaller a = new AutoInstaller(t.GetServerRoot());
+
+ ServerInfo s = new ServerInfo(t.GetServerRoot());
+ System.out.println (" Admin Port : " + s.GetAdminPort());
+ System.out.println (" LDAP Port : "+ s.GetConfigLDAPPort());
+ System.out.println( "Hostname " + s.GetHostName());
+ System.out.println(" doamin name : " + s.GetDomainName());
+
+ t.setHostName(s.GetHostName());
+ // Set adminServer Info
+ a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),s.GetDomainName(),"admin","admin");
+ a.setAdminInfo(s.GetHostName(),s.GetAdminPort(),"mcom.com","admin","admin");
+
+ // setCAInfo
+ a.setCAInfo(s.GetHostName(),"1027","8100","admin","secret12");
+ //setInternalDB info
+ String dp = t.getFreePort("38900");
+ a.setInternalDBInfo(s.GetHostName(),"38907","ca-db","cn=directory manager","secret12" );
+
+ // set tokenInfo
+
+ a.setTokenInfo("Internal","secret12");
+
+ // set Subsystem info
+ String agp = t.getFreePort("8100");
+ String adp = t.getFreePort("8200");
+ String eesp = t.getFreePort("1027");
+ String eep = t.getFreePort("1100");
+
+ System.out.println(agp);
+
+ a.setSubSystemInfo("testra",t.GetServerRoot(),"RSA","1024","MD5","365","cn=certificate manager,ou=test,o=test",adp,agp,eesp,eep);
+
+ a.setClientDBInfo(t.GetClientCertDB(),"secret12",t.GetAdminCertName());
+
+ a.ConfigureCA("admin","admin","secret12","secret12");
+
+ // a.ConfigureRA("admin","admin","secret12","secret12");
+
*/
/*
- * *****************************************************
- * Example to Get Server Details
- * *****************************************************
+ ******************************************************
+ * Example to Get Server Details
+ ******************************************************
*/
+
+
ServerInfo s = new ServerInfo(t.GetServerRoot(), t.GetInstanceRoot());
t.setHostName(s.GetHostName());
-
+
System.out.println("AgentPort " + s.GetAgentPort());
System.out.println("EESSLPort " + s.GetEESSLPort());
System.out.println("EEPort " + s.GetEEPort());
@@ -616,8 +620,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
System.out.println("CASigningCert:" + s.GetCASigningCert());
System.out.println("RASigningCert:" + s.GetRASigningCert());
System.out.println("ServerCert" + s.GetServerCertNickName());
- System.out.println("------------------------------------------");
- System.out.println(" Internal Database Test:");
+ System.out.println("------------------------------------------");
+ System.out.println(" Internal Database Test:");
System.out.println(" LDAP Port : " + s.GetConfigLDAPPort());
System.out.println("Hostname " + s.GetHostName());
@@ -629,319 +633,342 @@ public class TestClient implements SSLCertificateApprovalCallback {
/* ****************************************************************
* CMC Enroll
- * **************************************************************
+ ***************************************************************
*/
- /*
- * CMSUtils cmsutils = new CMSUtils(t.GetServerRoot()); String
- * requestfile=
- * "/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptance/data/basic/cmcreq/cmctest1.req"
- * ;
- * cmsutils.runCMCEnroll(t.GetClientCertDB(),"cn=admin",t.GetClientCertDBPW
- * (),requestfile); Profiles pr = new
- * Profiles(s.GetHostName(),s.GetEESSLPort());
- * pr.setProfileType("caCMCUserCert"); pr.setCertAuthority("ca");
- *
- * String request = t.readRequest(requestfile+".out"); String bstr =
- * "-----BEGIN NEW CERTIFICATE REQUEST-----"; String
- * estr="-----END NEW CERTIFICATE REQUEST-----"; String Blob1 =
- * request.substring(bstr.length() + 1); String Blob2 =
- * Blob1.substring(0,Blob1.indexOf(estr)); request=Blob2;
- *
- *
- * pr.setRequest(request);
- *
- * pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test",
- * "netscape","aol"); pr.clientCertEnroll();
+ /* CMSUtils cmsutils = new CMSUtils(t.GetServerRoot());
+ String requestfile="/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptance/data/basic/cmcreq/cmctest1.req";
+ cmsutils.runCMCEnroll(t.GetClientCertDB(),"cn=admin",t.GetClientCertDBPW(),requestfile);
+ Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
+ pr.setProfileType("caCMCUserCert");
+ pr.setCertAuthority("ca");
+
+ String request = t.readRequest(requestfile+".out");
+ String bstr = "-----BEGIN NEW CERTIFICATE REQUEST-----";
+ String estr="-----END NEW CERTIFICATE REQUEST-----";
+ String Blob1 = request.substring(bstr.length() + 1);
+ String Blob2 = Blob1.substring(0,Blob1.indexOf(estr));
+ request=Blob2;
+
+
+ pr.setRequest(request);
+
+ pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol");
+ pr.clientCertEnroll();
*/
+
/* ****************************************************************
* OCSP Client stuff
- * ***********************************************************
+ ************************************************************
*/
/*
- * String ip= "10.169.25.26"; OCSPClient ocspclient= new
- * OCSPClient(s.GetHostName
- * (),ip,s.GetEEPort(),t.GetClientCertDB(),t.GetClientCertDBPW
- * (),"cn=admin" ,"/tmp/ocsp.out","4");
- * ocspclient.setCert(t.findCertByNickname("ocsp-agent"));
- *
- * ocspclient.SendOCSPRequest();
+ String ip= "10.169.25.26";
+ OCSPClient ocspclient= new OCSPClient(s.GetHostName(),ip,s.GetEEPort(),t.GetClientCertDB(),t.GetClientCertDBPW(),"cn=admin" ,"/tmp/ocsp.out","4");
+ ocspclient.setCert(t.findCertByNickname("ocsp-agent"));
+
+ ocspclient.SendOCSPRequest();
*/
+
/*
- * ****************************************************
+ *****************************************************
* Test CRMFcleint and KRA REcovery and Archival
- * ****************************************************
+ *****************************************************
*/
/*
- * ********************************************************
+ *********************************************************
* OCSP Agent stuff
- * ********************************************************
+ *********************************************************
*/
- /*
- * Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort());
- * rtr.getCACert(); System.out.println("CA Cert chain" + rtr.getCert());
- *
- * OcspAgent ocspAgent= new OcspAgent(s.GetHostName(),"8111");
- * ocspAgent.setAgentCertName(t.GetOCSPAgentCertName());
- *
- * String cert = "-----BEGIN CERTIFICATE-----"+"\n"+rtr.getCert()+"\n"+
- * "-----END CERTIFICATE-----\n";
- *
- * ocspAgent.setCACert(cert); ocspAgent.addCA();
- */
- /*
- * **************************************************************
- * Submit Profile based request
- * ********************************************************
+ /* Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort());
+ rtr.getCACert();
+ System.out.println("CA Cert chain" + rtr.getCert());
+
+ OcspAgent ocspAgent= new OcspAgent(s.GetHostName(),"8111");
+ ocspAgent.setAgentCertName(t.GetOCSPAgentCertName());
+
+ String cert = "-----BEGIN CERTIFICATE-----"+"\n"+rtr.getCert()+"\n"+"-----END CERTIFICATE-----\n";
+
+ ocspAgent.setCACert(cert);
+ ocspAgent.addCA();
*/
+
/*
- * Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
- * pr.setProfileType("caUserCert"); //
- * pr.setProfileType("caDirUserCert");
- *
- * pr.setCertAuthority("ca");
- * pr.setUserInfo("UID=test1,Ou=netscape,o=aol"
- * ,"test","test","test","netscape","aol");
- * //pr.setDirUserInfo("test","netscape"); pr.clientCertEnroll();
- * System.out.println("Request ID is " + pr.getRequestID());
- *
- *
- * Request re = new Request (s.GetHostName(),s.GetAgentPort(),"ca");
- * re.setAgentCertName(t.GetAdminCertName());
- * re.ApproveProfileRequests(pr.getRequestID());
+ ***************************************************************
+ Submit Profile based request
+ *********************************************************
*/
/*
- * String TransportCert=
- * "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MjMyMTM3NTFaFw0wNDA0MjIwOTMzMzFaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVW81T7GatHIB25kF0jdY4h4hOF1NAlAHE2YdN/UEyXuU22CfwrIltA3x/6sKFHhbbFysn6nGJlgKipPJqJDwyYTIv07hgoXqgcUu8fSYQg4BDHYhpHJxsUt3BSfADTjxAUHize7C2F8TVhBIcWW043FSkwvAiUjJb7uqQRKn7lAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBTqvc3UPGDSWq+21DZGSUABNGIUbDANBgkqhkiG9w0BAQQFAAOBgQCNLJivNDHTTmCb2vDefUwLMxXNjuHwrbjVqymHPFqUjredTq2Yp+Ed1zxj+mxRovzegd65Tbnx+MV84j8K3Qc1kWOC+kbohAY9svSPsN3o5Q5BB19+5nUPC5Gk/mxkWJWWJLOnpKJGiAHMZIr58TH7hF8KQWXWMN9ikSFkPj0a/g=="
- * ;
- *
- *
- * CRMFClient CrmfClient = new
- * CRMFClient(s.GetHostName(),s.GetEEPort());
- * CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
- * CrmfClient.setTransportCert(TransportCert);
- * CrmfClient.setUserInfo("user","netscape");
- * CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
- * CrmfClient.setDualKey(true);
- *
- * if(!CrmfClient.Enroll())
- * {System.out.println("CRMFClient : could not submit request");}
- *
- *
- * checkRequest cr = new
- * checkRequest(s.GetHostName(),s.GetEESSLPort(),t.
- * getString(CrmfClient.getRequestId()),"false");
- * cr.checkRequestStatus(); System.out.println("Serial num " +
- * cr.getSerialNumber()); System.out.println("cert pack " +
- * cr.getCert());
- *
- * KraAgent kraAgent = new KraAgent(s.GetHostName(),"8111");
- * kraAgent.setAgentCertName("cn=admin");
- * System.out.println("KRAAgent List archival");
- *
- * Vector aReq= kraAgent.ListArchivalRequests(); int i=0; while(i <
- * aReq.size() ) { System.out.print(aReq.elementAt(i) + " "); i++; }
- *
- * kraAgent.setCertificate(cr.getCert()); kraAgent.setLocalAgent(false);
- * kraAgent.recoverKeys();
+ Profiles pr = new Profiles(s.GetHostName(),s.GetEESSLPort());
+ pr.setProfileType("caUserCert");
+ // pr.setProfileType("caDirUserCert");
+
+ pr.setCertAuthority("ca");
+ pr.setUserInfo("UID=test1,Ou=netscape,o=aol","test","test","test","netscape","aol");
+ //pr.setDirUserInfo("test","netscape");
+ pr.clientCertEnroll();
+ System.out.println("Request ID is " + pr.getRequestID());
+
+
+ Request re = new Request (s.GetHostName(),s.GetAgentPort(),"ca");
+ re.setAgentCertName(t.GetAdminCertName());
+ re.ApproveProfileRequests(pr.getRequestID());
*/
/*
- * ************************************************************
- * Example to Connect oto Config Directory port
- * ************************************************************
+ String TransportCert="MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MjMyMTM3NTFaFw0wNDA0MjIwOTMzMzFaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANVW81T7GatHIB25kF0jdY4h4hOF1NAlAHE2YdN/UEyXuU22CfwrIltA3x/6sKFHhbbFysn6nGJlgKipPJqJDwyYTIv07hgoXqgcUu8fSYQg4BDHYhpHJxsUt3BSfADTjxAUHize7C2F8TVhBIcWW043FSkwvAiUjJb7uqQRKn7lAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBTqvc3UPGDSWq+21DZGSUABNGIUbDANBgkqhkiG9w0BAQQFAAOBgQCNLJivNDHTTmCb2vDefUwLMxXNjuHwrbjVqymHPFqUjredTq2Yp+Ed1zxj+mxRovzegd65Tbnx+MV84j8K3Qc1kWOC+kbohAY9svSPsN3o5Q5BB19+5nUPC5Gk/mxkWJWWJLOnpKJGiAHMZIr58TH7hF8KQWXWMN9ikSFkPj0a/g==";
+
+
+ CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort());
+ CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
+ CrmfClient.setTransportCert(TransportCert);
+ CrmfClient.setUserInfo("user","netscape");
+ CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
+ CrmfClient.setDualKey(true);
+
+ if(!CrmfClient.Enroll())
+ {System.out.println("CRMFClient : could not submit request");}
+
+
+ checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(CrmfClient.getRequestId()),"false");
+ cr.checkRequestStatus();
+ System.out.println("Serial num " + cr.getSerialNumber());
+ System.out.println("cert pack " + cr.getCert());
+
+ KraAgent kraAgent = new KraAgent(s.GetHostName(),"8111");
+ kraAgent.setAgentCertName("cn=admin");
+ System.out.println("KRAAgent List archival");
+
+ Vector aReq= kraAgent.ListArchivalRequests();
+ int i=0;
+ while(i < aReq.size() )
+ {
+ System.out.print(aReq.elementAt(i) + " ");
+ i++;
+ }
+
+ kraAgent.setCertificate(cr.getCert());
+ kraAgent.setLocalAgent(false);
+ kraAgent.recoverKeys();
*/
/*
- * CMSLDAP cmsldap = new
- * CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.
- * GetLDAPDN(),t.GetLDAPDNPW()); if(cmsldap.connect())
- * System.out.println("LDAP Connection successful"); else
- * System.out.println("Error Connecting to LDAPSERVER");
- *
- * // Add user to config directoory if
- * (cmsldap.userAdd("ou=people,"+t.GetLDAPBASE
- * (),"t2","t2","t2","netscape"))
- * System.out.println("Added user to Config directory");
+ *************************************************************
+ * Example to Connect oto Config Directory port
+ *************************************************************
+ */
+
+ /*
+ CMSLDAP cmsldap = new CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.GetLDAPDN(),t.GetLDAPDNPW());
+ if(cmsldap.connect())
+ System.out.println("LDAP Connection successful");
+ else
+ System.out.println("Error Connecting to LDAPSERVER");
+
+ // Add user to config directoory
+ if (cmsldap.userAdd("ou=people,"+t.GetLDAPBASE(),"t2","t2","t2","netscape"))
+ System.out.println("Added user to Config directory");
+
*/
+
/*
- * ************************************************************
- * Example to Submit a CRMFCleint request to CA
- * ************************************************************
- */
+ *************************************************************
+ * Example to Submit a CRMFCleint request to CA
+ *************************************************************
+ */
String TransportCert = "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTgyMjMwMDhaFw0wNDA0MTcxMDI2MDhaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAN6sQ3mSU8mL6i6gTZIXDLzOZPhYOkQLpnJjit5hcPZ0JMn0CQVXo4QjKN1xvuZv8qVlZoQw9czmzp/knTa0sCDgFKd0r+u0TnLeZkJMSimgFnma9CnChlaDHnBd8Beu4vyaHmo7rJ0xA4etn7HjhmKbaQZOcv/aP0SW9JXRga7ZAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBSC3fsQHb7fddr2vL0UdkM2dAmUWzANBgkqhkiG9w0BAQQFAAOBgQBkAGbgd9HIqwoLKAr+V6bj9oWesDmDH80gPPxj10qyWSQYIs8PofOs/75yGS9nxhydtgSMFoBgCPdroUI31kZQQlFzxtudGoKD+5MWSXho79XzPwpjheOBYgpX6ch+L4tMLFDpqeraB1yZESO5EEeKm20DGVBOKVWxHhddO1BenA==";
/*
- * CRMFClient CrmfClient = new
- * CRMFClient(s.GetHostName(),s.GetEEPort());
- * CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
- * CrmfClient.setTransportCert(TransportCert);
- * CrmfClient.setUserInfo("user","netscape");
- * CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
- * CrmfClient.setDualKey(true);
- *
- * if(!CrmfClient.Enroll())
- * {System.out.println("CRMFClient : could not submit request");}
+ CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort());
+ CrmfClient.setDBInfo(t.GetClientCertDB(),t.GetClientCertDBPW());
+ CrmfClient.setTransportCert(TransportCert);
+ CrmfClient.setUserInfo("user","netscape");
+ CrmfClient.setLDAPInfo(t.GetLDAPDN(),t.GetLDAPDNPW());
+ CrmfClient.setDualKey(true);
+
+ if(!CrmfClient.Enroll())
+ {System.out.println("CRMFClient : could not submit request");}
*/
-
+
/* KRA Agent list archived request */
- /*
- * ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot()); String
- * KRAinstanceRoot=t.GetServerRoot() + "/cert-" + "KRARSA1024" ;
- * KRAsvrInfo.setInstanceRoot(KRAinstanceRoot);
- */
+ /* ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot());
+ String KRAinstanceRoot=t.GetServerRoot() + "/cert-" + "KRARSA1024" ;
+ KRAsvrInfo.setInstanceRoot(KRAinstanceRoot);*/
+
+ /* System.out.println("KRAAgent ");
+ KraAgent kraAgent = new KraAgent(s.GetHostName(),s.GetAgentPort());
+ kraAgent.setAgentCertName(t.GetKRAAgentCertName());
+ System.out.println("KRAAgent List archival");
+
+ Vector aReq= kraAgent.ListArchivalRequests();
+ int i=0;
+ while(i < aReq.size() )
+ {
+ System.out.print(aReq.elementAt(i) + " ");
+ i++;
+ }
- /*
- * System.out.println("KRAAgent "); KraAgent kraAgent = new
- * KraAgent(s.GetHostName(),s.GetAgentPort());
- * kraAgent.setAgentCertName(t.GetKRAAgentCertName());
- * System.out.println("KRAAgent List archival");
- *
- * Vector aReq= kraAgent.ListArchivalRequests(); int i=0; while(i <
- * aReq.size() ) { System.out.print(aReq.elementAt(i) + " "); i++; }
*/
+
// cmsldap.disconnect();
/*
- * ************************************************************
- * Example to submit manual user enrollment request
- * ************************************************************ /*
- *
- *
- * /* UserEnroll ue = new UserEnroll(s.GetHostName(),"1029");
- * ue.setUserInfo
- * ("E=testman,CN=testman,OU=netscape,O=aol,UID=testman1,C=US"
- * ,"testman", "testman", "testman1", "netscape","t");
- *
- * boolean flag = ue.clientCertEnroll(); if(flag)
- * System.out.println("Success submitted request");
+ *************************************************************
+ * Example to submit manual user enrollment request
+ *************************************************************
+ /*
+
+
+ /*
+ UserEnroll ue = new UserEnroll(s.GetHostName(),"1029");
+ ue.setUserInfo("E=testman,CN=testman,OU=netscape,O=aol,UID=testman1,C=US","testman", "testman", "testman1", "netscape","t");
+
+ boolean flag = ue.clientCertEnroll();
+ if(flag)
+ System.out.println("Success submitted request");
*/
/*
- * ************************************************************
- * Example to submit Directory based enroolemt request
- * ************************************************************ /*
- *
- * /* // Add user to config directoory if
- * (cmsldap.userAdd("dc=netscape,dc=com","t2","t2","t2","netscape"))
- * System.out.println("Success ");
- *
- * if(cmsldap.TurnOnSSL("slapd-jupiter2","Server-Cert cert-jupiter2","7000"
- * )) System.out.println("Turned on ssl"); else return;
- *
- * cmsldap.TurnOffSSL();
- *
- * cmsldap.disconnect();
- *
- * DirEnroll de = new DirEnroll(s.GetHostName(),s.GetEESSLPort());
- * de.setUIDInfo("t2","netscape"); de.enroll();
+ *************************************************************
+ * Example to submit Directory based enroolemt request
+ *************************************************************
+ /*
+
+ /*
+ // Add user to config directoory
+ if (cmsldap.userAdd("dc=netscape,dc=com","t2","t2","t2","netscape"))
+ System.out.println("Success ");
+
+ if(cmsldap.TurnOnSSL("slapd-jupiter2","Server-Cert cert-jupiter2","7000"))
+ System.out.println("Turned on ssl");
+ else
+ return;
+
+ cmsldap.TurnOffSSL();
+
+ cmsldap.disconnect();
+
+ DirEnroll de = new DirEnroll(s.GetHostName(),s.GetEESSLPort());
+ de.setUIDInfo("t2","netscape");
+ de.enroll();
+
*/
/*
- * ************************************************************
- * Example to submit Admin Enrollment request
- * ************************************************************ /*
- *
- * /*
- *
- * AdminEnroll ade = new
- * AdminEnroll("jupiter2","8200","cn=CMS Administrator,UID=admin,C=US"
- * ,"admin", "secret12"); flag = ade.Enroll(); if (flag)
- * System.out.println("adminEnrolled Successfully");
+ *************************************************************
+ * Example to submit Admin Enrollment request
+ *************************************************************
+ /*
+
+ /*
+
+ AdminEnroll ade = new AdminEnroll("jupiter2","8200","cn=CMS Administrator,UID=admin,C=US","admin", "secret12");
+ flag = ade.Enroll();
+ if (flag)
+ System.out.println("adminEnrolled Successfully");
*/
/*
- * ************************************************************
- * Example gent List Pending request
- * ************************************************************ /*
- *
- * /*
- *
- * // Agent List and Approve Request Request re = new Request
- * (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority());
- * re.setAgentCertName(t.GetAdminCertName());
- * re.ListPendingRequests("2","70");
- * re.ApproveRequests(t.getString(ue.getRequestId()));
+ *************************************************************
+ * Example gent List Pending request
+ *************************************************************
+ /*
+
+ /*
+
+ // Agent List and Approve Request
+ Request re = new Request (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority());
+ re.setAgentCertName(t.GetAdminCertName());
+ re.ListPendingRequests("2","70");
+ re.ApproveRequests(t.getString(ue.getRequestId()));
*/
/*
- * ************************************************************
- * Example for CheckRequest Status and add the certificate to internal
- * db************************************************************ /*
- *
- * /* // check request status and Revoke cert checkRequest cr = new
- * checkRequest
- * (s.GetHostName(),s.GetEESSLPort(),t.getString(ue.getRequestId
- * ()),"false"); checkRequest cr = new
- * checkRequest(s.GetHostName(),s.GetEESSLPort(),"1","false");
- *
- * cr.checkRequestStatus(); System.out.println("Serial num " +
- * cr.getSerialNumber()); System.out.println("cert pack " +
- * cr.getCert());
- *
- * String st= "-----BEGIN CERTIFICATE-----"+"\n"+cr.getCert()+"\n"+
- * "-----END CERTIFICATE-----\n"; System.out.println("cert pack " + st);
- *
- * cmsldap.getXCertificate(st.getBytes());
+ *************************************************************
+ * Example for CheckRequest Status and add the certificate to internal db
+ *************************************************************
+ /*
+
+ /*
+ // check request status and Revoke cert
+ checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),t.getString(ue.getRequestId()),"false");
+ checkRequest cr = new checkRequest(s.GetHostName(),s.GetEESSLPort(),"1","false");
+
+ cr.checkRequestStatus();
+ System.out.println("Serial num " + cr.getSerialNumber());
+ System.out.println("cert pack " + cr.getCert());
+
+ String st= "-----BEGIN CERTIFICATE-----"+"\n"+cr.getCert()+"\n"+"-----END CERTIFICATE-----\n";
+ System.out.println("cert pack " + st);
+
+ cmsldap.getXCertificate(st.getBytes());
+
*/
+
/*
- * ************************************************************
- * Example agent ro revoke request
- * ************************************************************ /*
- *
- * /* Revoke rr = new Revoke
- * (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority
- * (),t.getString(cr.getSerialNumber())); rr.revokeCerts();
+ *************************************************************
+ * Example agent ro revoke request
+ *************************************************************
+ /*
+
+ /*
+ Revoke rr = new Revoke (s.GetHostName(),s.GetAgentPort(),s.GetCertAuthority(),t.getString(cr.getSerialNumber()));
+ rr.revokeCerts();
*/
/*
- * ************************************************************
- * Example Agent update CRL
- * ************************************************************ /*
- *
- * /* // Update CRLand DISPLAY it
- *
- * System.out.println("Displayin CRL"); CRL crl = new CRL
- * (s.GetHostName(),s.GetAgentPort(),"/tmp/crlfile");
- * crl.setAgentCertName(t.GetAdminCertName()); crl.updateCRL();
- * crl.displayCRL(); crl.getRevokedCerts();
+ *************************************************************
+ * Example Agent update CRL
+ *************************************************************
+ /*
+
+ /*
+ // Update CRLand DISPLAY it
+
+ System.out.println("Displayin CRL");
+ CRL crl = new CRL (s.GetHostName(),s.GetAgentPort(),"/tmp/crlfile");
+ crl.setAgentCertName(t.GetAdminCertName());
+ crl.updateCRL();
+ crl.displayCRL();
+ crl.getRevokedCerts();
*/
// Update CRL in Directory
- /*
- * UpdateDir dcrl = new UpdateDir(s.GetHostName(),s.GetEESSLPort());
- * dcrl.updateDir();
- */
+ /* UpdateDir dcrl = new UpdateDir(s.GetHostName(),s.GetEESSLPort());
+ dcrl.updateDir();*/
/*
- * ************************************************************
- * Example for stopping and starting servers
- * ************************************************************
+ *************************************************************
+ * Example for stopping and starting servers
+ *************************************************************
*/
/*
- * DSTask idb = new DSTask(t.GetServerRoot()+"/slapd-jupiter2-db"); if
- * (idb.ldapStop()) System.out.println("IDB stopped");
- * if(idb.ldapStart()) System.out.println("IDB Started");
- *
- * System.out.println("------------------------------------------");
- * System.out.println(" CMS Test:"); CMSTask task = new
- * CMSTask(t.GetInstanceRoot()); task.CMSStop(); task.CMSStart();
+ DSTask idb = new DSTask(t.GetServerRoot()+"/slapd-jupiter2-db");
+ if (idb.ldapStop()) System.out.println("IDB stopped");
+ if(idb.ldapStart()) System.out.println("IDB Started");
+
+ System.out.println("------------------------------------------");
+ System.out.println(" CMS Test:");
+ CMSTask task = new CMSTask(t.GetInstanceRoot());
+ task.CMSStop();
+ task.CMSStart();
*/
+
+
}// end of function main
}
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java b/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
index 033a4d9d..fa402cf6 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,7 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,29 +29,32 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
+
+
/**
- * CMS Test framework . Submits Legacy Manual User Enrollment request from EESSL
- * port. Parses the response from server and return RequestID.
- * <P>
+ * CMS Test framework .
+ * Submits Legacy Manual User Enrollment request from EESSL port. Parses the response from server and return RequestID.
+ *<P>
*/
+
public class UserEnroll extends TestClient {
private int i;
- private String requestorName, requestorEmail, requestorPhone,
- requestorComments, requestId, certType, ssl_client;
+ private String requestorName, requestorEmail, requestorPhone, requestorComments, requestId, certType, ssl_client;
private int port;
private long elapsedTime;
// Constructor
- public UserEnroll() {
- }
+ public UserEnroll() {}
/**
- * Constructor . Takes the parameter hostname and EESSLport
+ * Constructor . Takes the parameter hostname and EESSLport
* <p>
*/
+
+
public UserEnroll(String h, String p) {
host = h;
ports = p;
@@ -60,28 +63,23 @@ public class UserEnroll extends TestClient {
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- *
- * @param propfilename name of the parameter file
+ * @param propfilename name of the parameter file
*/
+
public UserEnroll(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter for hostname, EESSLportnumber,
- * subjectdn, E, CN,UID,OU,O, CertdbDirecrory(fullpath) , certdbPassword,
- * keysize, keytype, requestorName,requestorEmail and Certtype. valid values
- * for Certtype - "ca","ra","ocsp"
+ * Constructor . Takes the parameter for hostname, EESSLportnumber, subjectdn, E, CN,UID,OU,O, CertdbDirecrory(fullpath) , certdbPassword, keysize, keytype, requestorName,requestorEmail and Certtype.
+ * valid values for Certtype - "ca","ra","ocsp"
* <p>
- *
- * @param propfilename name of the parameter file
+ * @param propfilename name of the parameter file
*/
- public UserEnroll(String h, String p, String dn, String e, String cn,
- String uid, String ou, String o, String cd, String tpwd,
- String sslcl, String ksize, String keyty, String reqname,
- String reqemail, String ctype) {
+
+ public UserEnroll(String h, String p, String dn, String e, String cn, String uid, String ou, String o, String cd, String tpwd, String sslcl, String ksize, String keyty, String reqname, String reqemail, String ctype) {
host = h;
ports = p;
@@ -117,12 +115,10 @@ public class UserEnroll extends TestClient {
}
/**
- * Set Certificate Request information. Takes parameters -
- * subjectdn,E,CN,UID,OU,O
+ * Set Certificate Request information. Takes parameters - subjectdn,E,CN,UID,OU,O
*/
- public void setUserInfo(String dn, String e, String cn, String uid,
- String ou, String o) {
+ public void setUserInfo(String dn, String e, String cn, String uid, String ou, String o) {
DN = dn;
E = e;
CN = cn;
@@ -137,8 +133,7 @@ public class UserEnroll extends TestClient {
}
- public void setUserInfo(String dn, String e, String cn, String uid,
- String ou, String o, String nickname) {
+ public void setUserInfo(String dn, String e, String cn, String uid, String ou, String o, String nickname) {
DN = dn;
E = e;
CN = cn;
@@ -154,8 +149,7 @@ public class UserEnroll extends TestClient {
}
/**
- * Set Certificat Type for which you want to submit a request . Valid values
- * - "ca"/"ra"/"ocsp"
+ * Set Certificat Type for which you want to submit a request . Valid values - "ca"/"ra"/"ocsp"
*/
public void setCertType(String ct) {
certType = ct;
@@ -168,22 +162,20 @@ public class UserEnroll extends TestClient {
public boolean enroll_load() {
buildquery();
setStatusString("");
- return (Send());
+ return(Send());
}
private boolean pkcs10() {
- System.out.println(" In pkcs10 Keysize , key type " + keysize
- + keytype);
- // ComCrypto cCrypt = new
- // ComCrypto(cdir,tokenpwd,certnickname,keysize,keytype);
+ System.out.println(" In pkcs10 Keysize , key type " + keysize + keytype);
+ // ComCrypto cCrypt = new ComCrypto(cdir,tokenpwd,certnickname,keysize,keytype);
cCrypt.setCertDir(cdir);
cCrypt.setCertnickname(adminCertName);
cCrypt.setKeySize(keysize);
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
cCrypt.setDebug(true);
- if (pkcs10request != null) {
+ if (pkcs10request != null) {
cCrypt.setGenerateRequest(false);
cCrypt.loginDB();
} else {
@@ -202,12 +194,12 @@ public class UserEnroll extends TestClient {
System.out.println(query);
}
setStatusString("");
- return (Send());
+ return(Send());
} catch (Exception e) {
System.err.println("some exception:" + e);
}
- return (false);
+ return(false);
}
@@ -234,7 +226,7 @@ public class UserEnroll extends TestClient {
try {
- if (debug) {
+ if (debug) {
System.out.println("Step 3 : Socket initialize");
}
@@ -261,8 +253,8 @@ public class UserEnroll extends TestClient {
ps.println("\r");
ps.flush();
os.flush();
- BufferedReader stdin = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ BufferedReader stdin = new BufferedReader(
+ new InputStreamReader(socket.getInputStream()));
if (debug) {
System.out.println("Step 4: Received the page");
@@ -278,10 +270,9 @@ public class UserEnroll extends TestClient {
st = true;
}
if (line.indexOf("fixed.requestId = ") != -1) {
- requestId = line.substring(
- "fixed.requestId = ".length() + 1,
+ requestId = line.substring("fixed.requestId = ".length() + 1,
line.indexOf(";") - 1);
- }
+ }
if (getError(line)) {
st = false;
@@ -309,7 +300,7 @@ public class UserEnroll extends TestClient {
}
return st;
-
+
}
private void buildquery() {
@@ -344,12 +335,12 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&csrRequestorEmail=");
queryStrBuf.append(URLEncoder.encode(requestorEmail));
queryStrBuf.append("&email=true");
-
+
} else {
queryStrBuf.append("&email=false");
}
-
- if (requestorPhone.length() > 0) {
+
+ if (requestorPhone.length() > 0) {
queryStrBuf.append("&csrRequestorPhone=");
queryStrBuf.append(URLEncoder.encode(requestorPhone));
}
@@ -357,7 +348,7 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&csrRequestorComments=");
queryStrBuf.append(URLEncoder.encode(requestorComments));
}
- System.out.println("buidlquery client E ");
+ System.out.println("buidlquery client E ");
if (E.length() > 0) {
queryStrBuf.append("&E=");
queryStrBuf.append(E);
@@ -375,10 +366,8 @@ public class UserEnroll extends TestClient {
queryStrBuf.append("&OU=");
queryStrBuf.append(OU);
}
- // if(O.length() > 0) {
- // queryStrBuf.append("&O=");queryStrBuf.append(O);}
- // if(C.length() >0) {
- // queryStrBuf.append("&C=");queryStrBuf.append(C);}
+ // if(O.length() > 0) { queryStrBuf.append("&O=");queryStrBuf.append(O);}
+ // if(C.length() >0) { queryStrBuf.append("&C=");queryStrBuf.append(C);}
System.out.println("buidlquery client dn ");
queryStrBuf.append("&subject=");
queryStrBuf.append(URLEncoder.encode(DN));
@@ -427,7 +416,7 @@ public class UserEnroll extends TestClient {
query = queryStrBuf.toString();
System.out.println(query);
- queryStrBuf = null;
+ queryStrBuf = null;
}
public int getRequestId() {
@@ -445,16 +434,16 @@ public class UserEnroll extends TestClient {
certType = "client";
ssl_client = "true";
debug = true;
- return (pkcs10());
+ return(pkcs10());
}
public boolean Enroll() {
debug = true;
- return (pkcs10());
+ return(pkcs10());
}
/**
- * Read the properties file
+ * Read the properties file
**/
public boolean readProperties() {
@@ -463,8 +452,8 @@ public class UserEnroll extends TestClient {
try {
getProperties(propfileName);
} catch (Exception e) {
- System.out.println("exception reading Properties File "
- + e.getMessage());
+ System.out.println(
+ "exception reading Properties File " + e.getMessage());
return false;
}
@@ -508,12 +497,12 @@ public class UserEnroll extends TestClient {
debug = false;
} else if (de.equals("true")) {
debug = true;
- } else {
+ } else {
debug = false;
}
// Enroll using a pkscks10 request
- return (pkcs10());
+ return(pkcs10());
}
public static void main(String args[]) {
@@ -521,33 +510,33 @@ public class UserEnroll extends TestClient {
// - requestId Pass
boolean st;
- UserEnroll e = new UserEnroll(
- "jupiter2",
- "1027",
- "E=test,cn=test,uid=test",
- "test",
- "test",
- "test",
- "t1",
- "t",
+ UserEnroll e = new UserEnroll("jupiter2", "1027",
+ "E=test,cn=test,uid=test", "test", "test", "test", "t1", "t",
"/u/lgopal/work/tetCMS/ns/tetframework/testcases/CMS/6.0/acceptanceJava/data/certdb",
"secret12", "true", "1024", "RSA", "rn", "re", "client");
e.clientCertEnroll();
-
- /*
- * if ( args.length < 1) { System.out.println("Usage : propertiesfile");
- * System.exit(0); }
- *
- *
- * UserEnroll t = new UserEnroll(args[0]); st=t.enroll(); if (st){
- * System
- * .out.println("User Enrolled successfully . RequestId is "+t.getrequestId
- * ()); System.exit(t.getRequestId()); } else{
- *
- * System.out.println("Error: " + t.getErrorDetail()); System.exit(0); }
+
+ /* if ( args.length < 1)
+ {
+ System.out.println("Usage : propertiesfile");
+ System.exit(0);
+ }
+
+
+ UserEnroll t = new UserEnroll(args[0]);
+ st=t.enroll();
+ if (st){
+ System.out.println("User Enrolled successfully . RequestId is "+t.getrequestId());
+ System.exit(t.getRequestId());
+ }
+ else{
+
+ System.out.println("Error: " + t.getErrorDetail());
+ System.exit(0);
+ }
*/
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java b/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
index 5a0b3b85..192ba056 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -85,7 +84,7 @@ public class Utilities {
StringBuffer buf = new StringBuffer();
int end = token.length();
int begin = 0;
-
+
if (token.endsWith(";")) {
end--;
}
@@ -160,8 +159,10 @@ public class Utilities {
}
/*
- * format of the file should be like this: -----BEGIN CERTIFICATE-----
- * base64 encoded certificate -----END CERTIFICATE-----
+ * format of the file should be like this:
+ * -----BEGIN CERTIFICATE-----
+ * base64 encoded certificate
+ * -----END CERTIFICATE-----
*/
public String getcertfromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -179,7 +180,7 @@ public class Utilities {
}
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcertfromfile" + e.toString());
@@ -202,15 +203,17 @@ public class Utilities {
}
return tempBuffer.toString();
} catch (Exception e) {
- System.out.println("ERROR: getcertfromfile_withheaders"
- + e.toString());
+ System.out.println(
+ "ERROR: getcertfromfile_withheaders" + e.toString());
return null;
}
}
/*
- * format of the file should be like this: -----BEGIN CERTIFICATE REVOCATION
- * LIST----- base64 encoded CRL -----END CERTIFICATE REVOCATION LIST-----
+ * format of the file should be like this:
+ * -----BEGIN CERTIFICATE REVOCATION LIST-----
+ * base64 encoded CRL
+ * -----END CERTIFICATE REVOCATION LIST-----
*/
public String getcrlfromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -224,7 +227,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcrlfromfile" + e.toString());
@@ -234,8 +237,10 @@ public class Utilities {
}
/*
- * format of the file should be like this: -----BEGIN CERTIFICATE-----
- * base64 encoded certificate -----END CERTIFICATE-----
+ * format of the file should be like this:
+ * -----BEGIN CERTIFICATE-----
+ * base64 encoded certificate
+ * -----END CERTIFICATE-----
*/
public String getcafromfile(String filename) {
StringBuffer tempBuffer = new StringBuffer();
@@ -249,7 +254,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcafromfile" + e.toString());
@@ -259,12 +264,12 @@ public class Utilities {
}
/*
- * function for RFC 2254. converts a x509 certificate given as a binary
- * array[] to a Ldap filter string
+ * function for RFC 2254. converts a x509 certificate given as
+ * a binary array[] to a Ldap filter string
*/
public static String escapeBinaryData(byte data[]) {
String result = "";
-
+
for (int i = 0; i < data.length; i++) {
String s = Integer.toHexString((int) (0xff & data[i]));
@@ -309,25 +314,23 @@ public class Utilities {
X509CertInfo certinfo = (X509CertInfo) x509_cert.get("x509.INFO");
/* Get Serial Number */
- CertificateSerialNumber csn = (CertificateSerialNumber) certinfo
- .get(X509CertInfo.SERIAL_NUMBER);
+ CertificateSerialNumber csn = (CertificateSerialNumber)
+ certinfo.get(X509CertInfo.SERIAL_NUMBER);
SerialNumber sn = (SerialNumber) csn.get("NUMBER");
- // just adding serialnumber for add.
- // we can add mode here like subject name, extensions,issuer to this
- // record.
+ // just adding serialnumber for add.
+ // we can add mode here like subject name, extensions,issuer to this record.
cr.serialNumber = sn.getNumber().toString().trim();
/* Get Subject Name */
- CertificateSubjectName csn1 = (CertificateSubjectName) certinfo
- .get(X509CertInfo.SUBJECT);
+ CertificateSubjectName csn1 = (CertificateSubjectName)
+ certinfo.get(X509CertInfo.SUBJECT);
@SuppressWarnings("unchecked")
- Enumeration<String> en = csn1.getElements();
+ Enumeration<String> en = csn1.getElements();
- X500Name dname = (X500Name) csn1
- .get(CertificateSubjectName.DN_NAME);
+ X500Name dname = (X500Name) csn1.get(CertificateSubjectName.DN_NAME);
String pp = "";
RDN[] rdns = dname.getNames();
@@ -339,8 +342,7 @@ public class Utilities {
cr.subject = pp;
} catch (Exception e) {
- System.out.println("ERROR: Exception when decoding certificate="
- + e);
+ System.out.println("ERROR: Exception when decoding certificate=" + e);
e.printStackTrace();
return null;
}
@@ -349,4 +351,7 @@ public class Utilities {
}
-}; // end class
+}
+
+
+; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java b/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
index 11eec6d4..f2a71085 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.common;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,6 +17,7 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
@@ -29,23 +29,23 @@ import java.util.GregorianCalendar;
import org.mozilla.jss.ssl.SSLSocket;
+
+
/**
- * CMS Test framework . Submits a checkRequestStatus request to the server.
- * parses the response from server and can import cert to the specified client
- * database.
- * <P>
+ * CMS Test framework .
+ * Submits a checkRequestStatus request to the server. parses the response from server and can import cert to the specified client database.
+ *<P>
*/
+
public class checkRequest extends TestClient {
private int i;
- private String certfile, importcert = "false", certnickname, serialNumber,
- ldapformat;
+ private String certfile, importcert = "false", certnickname, serialNumber, ldapformat;
private String requestId;
private String reqStatus = "false";
- private String pkcsCert, baseCert, ACTION_STRING, issuer, subject,
- AUTH = "ca";
+ private String pkcsCert, baseCert, ACTION_STRING, issuer, subject, AUTH = "ca";
private int port;
private boolean impStatus = false;
private int type = 1;
@@ -57,32 +57,32 @@ public class checkRequest extends TestClient {
private String tokenpwd;
private String cdir;
- // public methods
+ // public methods
/**
* Constructor . Takes the parameter for Properties file name
* <p>
- *
- * @param propfilename name of the parameter file
+ * @param propfilename name of the parameter file
*/
+
public checkRequest(String pfile) {
propfileName = pfile;
}
/**
- * Constructor . Takes the parameter for hostname and EESSLportnumber
+ * Constructor . Takes the parameter for hostname and EESSLportnumber
* <p>
*/
public checkRequest(String h, String p) {
host = h;
ports = p;
- };
+ }
+ ;
/**
- * Constructor . Takes the parameter for hostname , EESSLportnumber ,
- * Requestnumber and ImportCert ( true/false)
+ * Constructor . Takes the parameter for hostname , EESSLportnumber , Requestnumber and ImportCert ( true/false)
* <p>
*/
@@ -94,14 +94,12 @@ public class checkRequest extends TestClient {
}
/**
- * Constructor . Takes the parameter for hostname , EESSLportnumber ,
- * certdbdir, certdbpassword, Requestnumber ,certnickname and ImportCert (
- * true/false)
+ * Constructor . Takes the parameter for hostname , EESSLportnumber , certdbdir, certdbpassword, Requestnumber ,certnickname and ImportCert ( true/false)
* <p>
*/
- public checkRequest(String hs, String pt, String certdir,
- String certtokenpwd, String seqnum, String nickname, String impc) {
+
+ public checkRequest(String hs, String pt, String certdir, String certtokenpwd, String seqnum, String nickname, String impc) {
host = hs;
ports = pt;
cdir = certdir;
@@ -160,10 +158,11 @@ public class checkRequest extends TestClient {
}
/**
- * returns the hex serial number of the certificate
+ * returns the hex serial number of the certificate
**/
- public String getSerialNumberHex() {
+
+ public String getSerialNumberHex() {
return serialNumber;
}
@@ -171,7 +170,7 @@ public class checkRequest extends TestClient {
* returns the serial number as interger
**/
- public int getSerialNumber() {
+ public int getSerialNumber() {
if (serialNumber != null) {
Integer y = new Integer(Integer.parseInt(serialNumber, 16));
@@ -194,9 +193,9 @@ public class checkRequest extends TestClient {
cCrypt.setTokenPWD(tokenpwd);
cCrypt.setDebug(debug);
- if (!cCrypt.loginDB()) {
- System.out.println("Error : Login certdb failed ");
- System.err.println("FAIL : Login certdb failed ");
+ if (!cCrypt.loginDB()) {
+ System.out.println("Error : Login certdb failed ");
+ System.err.println("FAIL : Login certdb failed ");
return false;
}
@@ -248,11 +247,11 @@ public class checkRequest extends TestClient {
System.out.println(query);
}
setStatusString("Congratulations, your certificate has been issued");
- return (Send());
+ return(Send());
}
- // Private functions
+ // Private functions
private void setElapsedTime(long dif) {
elapsedTime = dif;
@@ -286,12 +285,12 @@ public class checkRequest extends TestClient {
tmp = cCrypt.normalizeForLDAP(getCert());
if (debug) {
System.out.println(tmp);
- }
+ }
fos.write(("usercertificate:: ").getBytes());
fos.write(tmp.getBytes());
fos.close();
} else {
- String tmp = cCrypt.normalize(getCert());
+ String tmp = cCrypt.normalize(getCert());
if (debug) {
System.out.println(tmp);
@@ -300,21 +299,21 @@ public class checkRequest extends TestClient {
fos.close();
}
-
+
} catch (Exception e) {
- System.out.println("exception in writeCert2File: "
- + e.getMessage());
+ System.out.println(
+ "exception in writeCert2File: " + e.getMessage());
return false;
}
- }
+ }
return true;
}
private boolean importCert(String certpack) {
- if (importcert.equals("false")) {
+ if (importcert.equals("false")) {
return true;
}
@@ -330,8 +329,8 @@ public class checkRequest extends TestClient {
+ "-----END CERTIFICATE-----";
if (debug) {
- System.out.println("importing cert" + tmp + "certnick"
- + certnickname);
+ System.out.println(
+ "importing cert" + tmp + "certnick" + certnickname);
}
s = tmp;
}
@@ -344,8 +343,8 @@ public class checkRequest extends TestClient {
return false;
} catch (Exception e) {
- System.out.println("exception importing cert crequest"
- + e.getMessage());
+ System.out.println(
+ "exception importing cert crequest" + e.getMessage());
return false;
}
@@ -367,8 +366,7 @@ public class checkRequest extends TestClient {
}
if (line.indexOf("header.pkcs7ChainBase64 = ") != -1) {
// if status is complete retrieve cert
- pkcsCert = line.substring(
- "header.pkcs7ChainBase64 = ".length() + 1,
+ pkcsCert = line.substring("header.pkcs7ChainBase64 = ".length() + 1,
line.indexOf(";", 10) - 1);
}
if (line.indexOf("record.serialNumber=") != -1) {
@@ -395,9 +393,9 @@ public class checkRequest extends TestClient {
boolean st = true;
- String retriveStr[] = { "record.base64Cert=",
- "record.certPrettyPrint=", "header.certChainBase64 = ",
- "header.certPrettyPrint = " };
+ String retriveStr[] = {
+ "record.base64Cert=", "record.certPrettyPrint=",
+ "header.certChainBase64 = ", "header.certPrettyPrint = "};
String baseCertStr, certPrettyprintStr;
if (AUTH.equals("ra")) {
@@ -407,19 +405,19 @@ public class checkRequest extends TestClient {
baseCertStr = retriveStr[2];
certPrettyprintStr = retriveStr[3];
}
-
+
if (line.indexOf(baseCertStr) != -1) {
// if status is complete retrieve cert
baseCert = line.substring(baseCertStr.length() + 1,
line.indexOf(";", 10) - 1);
if (importcert.equals("true")) {
- if (importCert(baseCert)) {
+ if (importCert(baseCert)) {
st = true;
}
} else {
st = true;
- }
+ }
}
if (line.indexOf(certPrettyprintStr) != -1) {
@@ -480,8 +478,8 @@ public class checkRequest extends TestClient {
ps.println("\r");
ps.flush();
os.flush();
- BufferedReader stdin = new BufferedReader(new InputStreamReader(
- socket.getInputStream()));
+ BufferedReader stdin = new BufferedReader(
+ new InputStreamReader(socket.getInputStream()));
if (debug) {
System.out.println("Step 4: Received the page");
@@ -491,9 +489,9 @@ public class checkRequest extends TestClient {
while ((line = stdin.readLine()) != null) {
switch (type) {
- case 1:
+ case 1:
RetrieveRequestDetail(line);
- st = true;
+ st = true;
break;
case 2:
@@ -504,7 +502,7 @@ public class checkRequest extends TestClient {
System.out.println("invalid format");
}
-
+
}
stdin.close();
socket.close();
@@ -533,9 +531,9 @@ public class checkRequest extends TestClient {
if (debug) {
System.out.println(serialNumber);
}
-
+
return st;
-
+
}
private void buildquery() {
@@ -543,7 +541,7 @@ public class checkRequest extends TestClient {
StringBuffer queryStrBuf = new StringBuffer();
if (type == 1) {
- ACTION_STRING = "/checkRequest";
+ ACTION_STRING = "/checkRequest";
queryStrBuf.append("requestId=");
queryStrBuf.append(requestId);
queryStrBuf.append("&importCert=true");
@@ -576,8 +574,8 @@ public class checkRequest extends TestClient {
try {
getProperties(propfileName);
} catch (Exception e) {
- System.out.println("exception reading Properties File "
- + e.getMessage());
+ System.out.println(
+ "exception reading Properties File " + e.getMessage());
return false;
}
@@ -608,23 +606,23 @@ public class checkRequest extends TestClient {
}
// Enroll using a pkscks10 request
- return (checkRequestStatus());
+ return(checkRequestStatus());
}
public static void main(String args[]) {
// Exit Status - (0) for error/Fail
// - requestId Pass
boolean st;
-
+
if (args.length < 1) {
System.out.println("Usage : propertiesfile");
System.exit(0);
- }
+ }
checkRequest t = new checkRequest(args[0]);
st = t.readProperties();
- if (st) {
+ if (st) {
System.exit(t.getSerialNumber());
} else {
@@ -635,5 +633,5 @@ public class checkRequest extends TestClient {
}
}// end of function main
-} // end of class
+} // end of class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java b/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
index ff541b6c..078bb588 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.http;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -22,24 +21,28 @@ import java.util.Vector;
import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
-public class CertSelection implements SSLClientCertificateSelectionCallback {
- // make the select() call to use this client cert
- public static String client_cert = null;
+public class CertSelection implements SSLClientCertificateSelectionCallback
+{
+
+ // make the select() call to use this client cert
+ public static String client_cert = null;
- public void setClientCert(String nickname) {
- client_cert = nickname;
- }
+ public void setClientCert(String nickname)
+ {
+ client_cert = nickname;
+ }
- public String select(@SuppressWarnings("rawtypes") Vector nicknames) {
+ public String select(@SuppressWarnings("rawtypes") Vector nicknames)
+ {
- // when this method is called by SSLSocket we get a vector
- // of nicknames to select similar to the way the browser presents
- // the list.
+ // when this method is called by SSLSocket we get a vector
+ // of nicknames to select similar to the way the browser presents
+ // the list.
- // We will just use the one thats set by setClientCert()
+ // We will just use the one thats set by setClientCert()
- return client_cert;
- }
+ return client_cert;
+ }
}; // end class
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
index 5c655649..df95f861 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.http;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -26,584 +25,727 @@ import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-public class HTMLDocument {
- // Indicates whether this HTML document has been parsed.
- boolean parsed;
-
- // A list of URLs of files that should be retrieved along with the main
- // contents of the document. This may include any images contained in the
- // document, and possibly any external stylesheets.
- LinkedHashSet<String> associatedFiles;
-
- // A list of URLs of frames that are contained in the document.
- LinkedHashSet<String> documentFrames;
-
- // A list of URLs of links that are contained in the document.
- LinkedHashSet<String> documentLinks;
-
- // A list of URLs of images that are contained in the document.
- LinkedHashSet<String> documentImages;
-
- // A regular expression pattern that can be used to extract a URI from an
- // HREF
- // tag.
- Pattern hrefPattern;
-
- // A regular expression pattern that can be used to extract a URI from a SRC
- // tag.
- Pattern srcPattern;
-
- // The base URL for relative links in this document.
- String baseURL;
-
- // The URL that may be used to access this document.
- String documentURL;
-
- // The actual contents of the page.
- String htmlData;
-
- // The contents of the page converted to lowercase for easier matching.
- String lowerData;
-
- // The URL for this document with only protocol, host, and port (i.e., no
- // file).
- String protocolHostPort;
-
- // A string buffer containing the contents of the page with tags removed.
- StringBuffer textData;
-
- // A set of private variables used for internal processing.
- private boolean lastElementIsAssociatedFile;
- private boolean lastElementIsChunk;
- private boolean lastElementIsComment;
- private boolean lastElementIsFrame;
- private boolean lastElementIsImage;
- private boolean lastElementIsLink;
- private boolean lastElementIsText;
- private int lastElementEndPos;
- private int lastElementStartPos;
- private String lastURL;
-
- // constructor that helps to parse without url stuff
- public HTMLDocument(String htmlData) {
- this.documentURL = null;
- this.htmlData = htmlData;
- lowerData = htmlData.toLowerCase();
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
-
- // Create the regex patterns that we will use for extracting URIs from
- // tags.
- hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+"
- + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+"
- + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
+
+
+public class HTMLDocument
+{
+ // Indicates whether this HTML document has been parsed.
+ boolean parsed;
+
+ // A list of URLs of files that should be retrieved along with the main
+ // contents of the document. This may include any images contained in the
+ // document, and possibly any external stylesheets.
+ LinkedHashSet<String> associatedFiles;
+
+ // A list of URLs of frames that are contained in the document.
+ LinkedHashSet<String> documentFrames;
+
+ // A list of URLs of links that are contained in the document.
+ LinkedHashSet<String> documentLinks;
+
+ // A list of URLs of images that are contained in the document.
+ LinkedHashSet<String> documentImages;
+
+ // A regular expression pattern that can be used to extract a URI from an HREF
+ // tag.
+ Pattern hrefPattern;
+
+ // A regular expression pattern that can be used to extract a URI from a SRC
+ // tag.
+ Pattern srcPattern;
+
+ // The base URL for relative links in this document.
+ String baseURL;
+
+ // The URL that may be used to access this document.
+ String documentURL;
+
+ // The actual contents of the page.
+ String htmlData;
+
+ // The contents of the page converted to lowercase for easier matching.
+ String lowerData;
+
+ // The URL for this document with only protocol, host, and port (i.e., no
+ // file).
+ String protocolHostPort;
+
+ // A string buffer containing the contents of the page with tags removed.
+ StringBuffer textData;
+
+
+ // A set of private variables used for internal processing.
+ private boolean lastElementIsAssociatedFile;
+ private boolean lastElementIsChunk;
+ private boolean lastElementIsComment;
+ private boolean lastElementIsFrame;
+ private boolean lastElementIsImage;
+ private boolean lastElementIsLink;
+ private boolean lastElementIsText;
+ private int lastElementEndPos;
+ private int lastElementStartPos;
+ private String lastURL;
+
+ // constructor that helps to parse without url stuff
+ public HTMLDocument(String htmlData)
+ {
+ this.documentURL = null;
+ this.htmlData = htmlData;
+ lowerData = htmlData.toLowerCase();
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
+
+
+ // Create the regex patterns that we will use for extracting URIs from tags.
+ hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
+ "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
+ srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
+ "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
+ }
+
+
+ /**
+ * Creates a new HTML document using the provided data.
+ *
+ * @param documentURL The URL for this document.
+ * @param htmlData The actual data contained in the HTML document.
+ */
+ public HTMLDocument(String documentURL, String htmlData)
+ throws MalformedURLException
+ {
+ this.documentURL = documentURL;
+ this.htmlData = htmlData;
+ lowerData = htmlData.toLowerCase();
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
+
+
+ // Create the regex patterns that we will use for extracting URIs from tags.
+ hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
+ "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
+ srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
+ "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
+
+ URL url = new URL(documentURL);
+ String urlPath = url.getPath();
+ if ((urlPath == null) || (urlPath.length() == 0))
+ {
+ baseURL = documentURL;
+ protocolHostPort = documentURL;
+ }
+ else if (urlPath.equals("/"))
+ {
+ baseURL = documentURL;
+ protocolHostPort = documentURL.substring(0, documentURL.length()-1);
+ }
+ else if (urlPath.endsWith("/"))
+ {
+ baseURL = documentURL;
+
+ int port = url.getPort();
+ if (port > 0)
+ {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
+ port;
+ }
+ else
+ {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost();
+ }
+ }
+ else
+ {
+ int port = url.getPort();
+ if (port > 0)
+ {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
+ port;
+ }
+ else
+ {
+ protocolHostPort = url.getProtocol() + "://" + url.getHost();
+ }
+
+ File urlFile = new File(urlPath);
+ String parentDirectory = urlFile.getParent();
+ if ((parentDirectory == null) || (parentDirectory.length() == 0))
+ {
+ parentDirectory = "/";
+ }
+ else if (! parentDirectory.startsWith("/"))
+ {
+ parentDirectory = "/" + parentDirectory;
+ }
+
+ baseURL = protocolHostPort + parentDirectory;
}
- /**
- * Creates a new HTML document using the provided data.
- *
- * @param documentURL The URL for this document.
- * @param htmlData The actual data contained in the HTML document.
- */
- public HTMLDocument(String documentURL, String htmlData)
- throws MalformedURLException {
- this.documentURL = documentURL;
- this.htmlData = htmlData;
- lowerData = htmlData.toLowerCase();
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
-
- // Create the regex patterns that we will use for extracting URIs from
- // tags.
- hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+"
- + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
- srcPattern = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+"
- + "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
-
- URL url = new URL(documentURL);
- String urlPath = url.getPath();
- if ((urlPath == null) || (urlPath.length() == 0)) {
- baseURL = documentURL;
- protocolHostPort = documentURL;
- } else if (urlPath.equals("/")) {
- baseURL = documentURL;
- protocolHostPort = documentURL.substring(0,
- documentURL.length() - 1);
- } else if (urlPath.endsWith("/")) {
- baseURL = documentURL;
-
- int port = url.getPort();
- if (port > 0) {
- protocolHostPort = url.getProtocol() + "://" + url.getHost()
- + ":" + port;
- } else {
- protocolHostPort = url.getProtocol() + "://" + url.getHost();
- }
- } else {
- int port = url.getPort();
- if (port > 0) {
- protocolHostPort = url.getProtocol() + "://" + url.getHost()
- + ":" + port;
- } else {
- protocolHostPort = url.getProtocol() + "://" + url.getHost();
- }
+ if (! baseURL.endsWith("/"))
+ {
+ baseURL = baseURL + "/";
+ }
+ }
- File urlFile = new File(urlPath);
- String parentDirectory = urlFile.getParent();
- if ((parentDirectory == null) || (parentDirectory.length() == 0)) {
- parentDirectory = "/";
- } else if (!parentDirectory.startsWith("/")) {
- parentDirectory = "/" + parentDirectory;
- }
- baseURL = protocolHostPort + parentDirectory;
+
+ /**
+ * Actually parses the HTML document and extracts useful elements from it.
+ *
+ * @return <CODE>true</CODE> if the page could be parsed successfully, or
+ * <CODE>false</CODE> if not.
+ */
+ public boolean parse()
+ {
+ if (parsed)
+ {
+ return true;
+ }
+
+
+ try
+ {
+ associatedFiles = new LinkedHashSet<String>();
+ documentFrames = new LinkedHashSet<String>();
+ documentLinks = new LinkedHashSet<String>();
+ documentImages = new LinkedHashSet<String>();
+ textData = new StringBuffer();
+
+ lastElementStartPos = 0;
+ lastElementEndPos = -1;
+ String element;
+ while ((element = nextDocumentElement()) != null)
+ {
+ if (element.length() == 0)
+ {
+ continue;
}
- if (!baseURL.endsWith("/")) {
- baseURL = baseURL + "/";
+ if (lastElementIsText)
+ {
+ char lastChar;
+ if (textData.length() == 0)
+ {
+ lastChar = ' ';
+ }
+ else
+ {
+ lastChar = textData.charAt(textData.length()-1);
+ }
+ char firstChar = element.charAt(0);
+ if (! ((lastChar == ' ') || (lastChar == '\t') ||
+ (lastChar == '\r') || (lastChar == '\n')) ||
+ (firstChar == ' ') || (firstChar == '\t') ||
+ (firstChar == '\r') || (firstChar == '\n'))
+ {
+ textData.append(" ");
+ }
+
+ textData.append(element);
+ }
+ else if (lastElementIsImage)
+ {
+ if (lastURL != null)
+ {
+ documentImages.add(lastURL);
+ associatedFiles.add(lastURL);
+ }
+ }
+ else if (lastElementIsFrame)
+ {
+ if (lastURL != null)
+ {
+ documentFrames.add(lastURL);
+ associatedFiles.add(lastURL);
+ }
+ }
+ else if (lastElementIsLink)
+ {
+ if (lastURL != null)
+ {
+ documentLinks.add(lastURL);
+ }
+ }
+ else if (lastElementIsAssociatedFile)
+ {
+ if (lastURL != null)
+ {
+ associatedFiles.add(lastURL);
+ }
+ }
+ else if (lastElementIsChunk || lastElementIsComment)
+ {
+ // Don't need to do anything with this.
}
+ else
+ {
+ // Also don't need anything here.
+ }
+ }
+
+ parsed = true;
+ }
+ catch (Exception e)
+ {
+ associatedFiles = null;
+ documentLinks = null;
+ documentImages = null;
+ textData = null;
+ parsed = false;
}
- /**
- * Actually parses the HTML document and extracts useful elements from it.
- *
- * @return <CODE>true</CODE> if the page could be parsed successfully, or
- * <CODE>false</CODE> if not.
- */
- public boolean parse() {
- if (parsed) {
- return true;
- }
+ return parsed;
+ }
- try {
- associatedFiles = new LinkedHashSet<String>();
- documentFrames = new LinkedHashSet<String>();
- documentLinks = new LinkedHashSet<String>();
- documentImages = new LinkedHashSet<String>();
- textData = new StringBuffer();
-
- lastElementStartPos = 0;
- lastElementEndPos = -1;
- String element;
- while ((element = nextDocumentElement()) != null) {
- if (element.length() == 0) {
- continue;
- }
-
- if (lastElementIsText) {
- char lastChar;
- if (textData.length() == 0) {
- lastChar = ' ';
- } else {
- lastChar = textData.charAt(textData.length() - 1);
- }
- char firstChar = element.charAt(0);
- if (!((lastChar == ' ') || (lastChar == '\t')
- || (lastChar == '\r') || (lastChar == '\n'))
- || (firstChar == ' ')
- || (firstChar == '\t')
- || (firstChar == '\r') || (firstChar == '\n')) {
- textData.append(" ");
- }
-
- textData.append(element);
- } else if (lastElementIsImage) {
- if (lastURL != null) {
- documentImages.add(lastURL);
- associatedFiles.add(lastURL);
- }
- } else if (lastElementIsFrame) {
- if (lastURL != null) {
- documentFrames.add(lastURL);
- associatedFiles.add(lastURL);
- }
- } else if (lastElementIsLink) {
- if (lastURL != null) {
- documentLinks.add(lastURL);
- }
- } else if (lastElementIsAssociatedFile) {
- if (lastURL != null) {
- associatedFiles.add(lastURL);
- }
- } else if (lastElementIsChunk || lastElementIsComment) {
- // Don't need to do anything with this.
- } else {
- // Also don't need anything here.
- }
- }
- parsed = true;
- } catch (Exception e) {
- associatedFiles = null;
- documentLinks = null;
- documentImages = null;
- textData = null;
- parsed = false;
- }
- return parsed;
+ /**
+ * Retrieves the next element from the HTML document. An HTML element can
+ * include a string of plain text, a single HTML tag, or a larger chunk of
+ * HTML including a start and end tag, all of which should be considered a
+ * single element.
+ */
+ private String nextDocumentElement()
+ {
+ // If we're at the end of the HTML, then return null.
+ if (lastElementEndPos >= htmlData.length())
+ {
+ return null;
}
- /**
- * Retrieves the next element from the HTML document. An HTML element can
- * include a string of plain text, a single HTML tag, or a larger chunk of
- * HTML including a start and end tag, all of which should be considered a
- * single element.
- */
- private String nextDocumentElement() {
- // If we're at the end of the HTML, then return null.
- if (lastElementEndPos >= htmlData.length()) {
- return null;
- }
- // Initialize the variables we will use for the search.
- lastElementStartPos = lastElementEndPos + 1;
- lastElementIsAssociatedFile = false;
- lastElementIsChunk = false;
- lastElementIsComment = false;
- lastElementIsFrame = false;
- lastElementIsImage = false;
- lastElementIsLink = false;
- lastElementIsText = false;
- lastURL = null;
-
- // Find the location of the next open angle bracket. If there is none,
- // then
- // the rest of the document must be plain text.
- int openPos = lowerData.indexOf('<', lastElementStartPos);
- if (openPos < 0) {
- lastElementEndPos = htmlData.length();
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos);
- }
+ // Initialize the variables we will use for the search.
+ lastElementStartPos = lastElementEndPos+1;
+ lastElementIsAssociatedFile = false;
+ lastElementIsChunk = false;
+ lastElementIsComment = false;
+ lastElementIsFrame = false;
+ lastElementIsImage = false;
+ lastElementIsLink = false;
+ lastElementIsText = false;
+ lastURL = null;
+
+
+ // Find the location of the next open angle bracket. If there is none, then
+ // the rest of the document must be plain text.
+ int openPos = lowerData.indexOf('<', lastElementStartPos);
+ if (openPos < 0)
+ {
+ lastElementEndPos = htmlData.length();
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos);
+ }
- // If the location of the next open tag is not we started looking, then
- // read
- // everything up to that tag as text.
- if (openPos > lastElementStartPos) {
- lastElementEndPos = openPos - 1;
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos, openPos);
- }
- // The start position is an open tag. See if the tag is actually "<!--",
- // which indicates an HTML comment. If that's the case, then find the
- // closing "-->".
- if (openPos == lowerData.indexOf("<!--", lastElementStartPos)) {
- int closePos = lowerData.indexOf("-->", openPos + 1);
- if (closePos < 0) {
- // This looks like an unterminated comment. We can't do much
- // else
- // here, so just stop parsing.
- return null;
- } else {
- lastElementEndPos = closePos + 2;
- lastElementIsComment = true;
- return htmlData.substring(lastElementStartPos,
- lastElementEndPos + 1);
- }
- }
+ // If the location of the next open tag is not we started looking, then read
+ // everything up to that tag as text.
+ if (openPos > lastElementStartPos)
+ {
+ lastElementEndPos = openPos-1;
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos, openPos);
+ }
- // Find the location of the next close angle bracket. If there is none,
- // then we have an unmatched open tag. What to do here? I guess just
- // treat
- // the rest of the document as text.
- int closePos = lowerData.indexOf('>', openPos + 1);
- if (closePos < 0) {
- lastElementEndPos = htmlData.length();
- lastElementIsText = true;
- return htmlData.substring(lastElementStartPos);
- }
- // Grab the contents of the tag in both normal and lowercase.
- String tag = htmlData.substring(openPos, closePos + 1);
- String strippedTag = htmlData.substring(openPos + 1, closePos).trim();
- StringTokenizer tokenizer = new StringTokenizer(strippedTag,
- " \t\r\n=\"'");
- lastElementEndPos = closePos;
+ // The start position is an open tag. See if the tag is actually "<!--",
+ // which indicates an HTML comment. If that's the case, then find the
+ // closing "-->".
+ if (openPos == lowerData.indexOf("<!--", lastElementStartPos))
+ {
+ int closePos = lowerData.indexOf("-->", openPos+1);
+ if (closePos < 0)
+ {
+ // This looks like an unterminated comment. We can't do much else
+ // here, so just stop parsing.
+ return null;
+ }
+ else
+ {
+ lastElementEndPos = closePos + 2;
+ lastElementIsComment = true;
+ return htmlData.substring(lastElementStartPos, lastElementEndPos+1);
+ }
+ }
- if (!tokenizer.hasMoreTokens()) {
- return tag;
- }
- String token = tokenizer.nextToken();
- String lowerToken = token.toLowerCase();
-
- if (lowerToken.equals("a") || lowerToken.equals("area")) {
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href")) {
- try {
- Matcher matcher = hrefPattern.matcher(tag);
- lastURL = uriToURL(matcher.replaceAll("$1"));
- if (lastURL != null) {
- lastElementIsLink = true;
- }
- } catch (Exception e) {
- }
- break;
- }
- }
- } else if (lowerToken.equals("base")) {
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href")) {
- try {
- Matcher matcher = hrefPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- if (!uri.endsWith("/")) {
- uri = uri + "/";
- }
-
- baseURL = uri;
- } catch (Exception e) {
- }
- break;
- }
- }
- } else if (lowerToken.equals("frame") || lowerToken.equals("iframe")
- || lowerToken.equals("input")) {
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src")) {
- try {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null) {
- lastElementIsFrame = true;
- lastElementIsAssociatedFile = true;
- }
- } catch (Exception e) {
- }
- break;
- }
- }
- } else if (lowerToken.equals("img")) {
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src")) {
- try {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null) {
- lastElementIsImage = true;
- }
- } catch (Exception e) {
- }
- break;
- }
- }
- } else if (lowerToken.equals("link")) {
- boolean isStyleSheet = false;
-
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("href")) {
- try {
- Matcher matcher = hrefPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- if (lastURL != null) {
- lastElementIsLink = true;
- }
- } catch (Exception e) {
- }
- break;
- } else if (token.equalsIgnoreCase("rel")) {
- if (tokenizer.hasMoreTokens()) {
- String relType = tokenizer.nextToken();
- if (relType.equalsIgnoreCase("stylesheet")) {
- isStyleSheet = true;
- }
- }
- }
- }
+ // Find the location of the next close angle bracket. If there is none,
+ // then we have an unmatched open tag. What to do here? I guess just treat
+ // the rest of the document as text.
+ int closePos = lowerData.indexOf('>', openPos+1);
+ if (closePos < 0)
+ {
+ lastElementEndPos = htmlData.length();
+ lastElementIsText = true;
+ return htmlData.substring(lastElementStartPos);
+ }
- if (lastURL != null) {
- if (isStyleSheet) {
- lastElementIsAssociatedFile = true;
- } else {
- lastElementIsLink = true;
- }
- }
- } else if (lowerToken.equals("script")) {
- while (tokenizer.hasMoreTokens()) {
- token = tokenizer.nextToken();
- if (token.equalsIgnoreCase("src")) {
- try {
- Matcher matcher = srcPattern.matcher(tag);
- String uri = matcher.replaceAll("$1");
- lastURL = uriToURL(uri);
- } catch (Exception e) {
- }
- break;
- }
- }
- if (lastURL == null) {
- int endScriptPos = lowerData.indexOf("</script>",
- lastElementEndPos + 1);
- if (endScriptPos > 0) {
- lastElementEndPos = endScriptPos + 8;
- tag = htmlData.substring(lastElementStartPos,
- lastElementEndPos + 1);
- lastElementIsChunk = true;
- }
- } else {
- lastElementIsAssociatedFile = true;
- }
- }
+ // Grab the contents of the tag in both normal and lowercase.
+ String tag = htmlData.substring(openPos, closePos+1);
+ String strippedTag = htmlData.substring(openPos+1, closePos).trim();
+ StringTokenizer tokenizer = new StringTokenizer(strippedTag, " \t\r\n=\"'");
+ lastElementEndPos = closePos;
- return tag;
+ if (! tokenizer.hasMoreTokens())
+ {
+ return tag;
}
- /**
- * Converts the provided URI to a URL. The provided URI may be a URL
- * already, or it may also be an absolute path on the server or a path
- * relative to the base URL.
- *
- * @param uri The URI to convert to a URL.
- *
- * @return The URL based on the provided URI.
- */
- private String uriToURL(String uri) {
- String url = null;
-
- if (uri.indexOf("://") > 0) {
- if (uri.startsWith("http")) {
- url = uri;
+ String token = tokenizer.nextToken();
+ String lowerToken = token.toLowerCase();
+
+ if (lowerToken.equals("a") || lowerToken.equals("area"))
+ {
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href"))
+ {
+ try
+ {
+ Matcher matcher = hrefPattern.matcher(tag);
+ lastURL = uriToURL(matcher.replaceAll("$1"));
+ if (lastURL != null)
+ {
+ lastElementIsLink = true;
}
- } else if (uri.startsWith("/")) {
- url = protocolHostPort + uri;
- } else {
- url = baseURL + uri;
+ } catch (Exception e) {}
+ break;
}
-
- return url;
+ }
}
+ else if (lowerToken.equals("base"))
+ {
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href"))
+ {
+ try
+ {
+ Matcher matcher = hrefPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ if (! uri.endsWith("/"))
+ {
+ uri = uri + "/";
+ }
- /**
- * Retrieves the URL of this HTML document.
- *
- * @return The URL of this HTML document.
- */
- public String getDocumentURL() {
- return documentURL;
+ baseURL = uri;
+ } catch (Exception e) {}
+ break;
+ }
+ }
}
-
- /**
- * Retrieves the original HTML data used to create this document.
- *
- * @return The orginal HTML data used to create this document.
- */
- public String getHTMLData() {
- return htmlData;
+ else if (lowerToken.equals("frame") || lowerToken.equals("iframe") ||
+ lowerToken.equals("input"))
+ {
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src"))
+ {
+ try
+ {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null)
+ {
+ lastElementIsFrame = true;
+ lastElementIsAssociatedFile = true;
+ }
+ } catch (Exception e) {}
+ break;
+ }
+ }
}
-
- /**
- * Retrieves the contents of the HTML document with all tags removed.
- *
- * @return The contents of the HTML document with all tags removed, or
- * <CODE>null</CODE> if a problem occurs while trying to parse the
- * HTML.
- */
- public String getTextData() {
- if (!parsed) {
- if (!parse()) {
- return null;
+ else if (lowerToken.equals("img"))
+ {
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src"))
+ {
+ try
+ {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null)
+ {
+ lastElementIsImage = true;
}
+ } catch (Exception e) {}
+ break;
}
-
- return textData.toString();
+ }
}
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference files that would normally be downloaded as part of
- * retrieving a page in a browser. This includes images and external style
- * sheets.
- *
- * @return An array containing a set of URLs to files associated with the
- * HTML document, or <CODE>null</CODE> if a problem occurs while
- * trying to parse the HTML.
- */
- public String[] getAssociatedFiles() {
- if (!parsed) {
- if (!parse()) {
- return null;
+ else if (lowerToken.equals("link"))
+ {
+ boolean isStyleSheet = false;
+
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("href"))
+ {
+ try
+ {
+ Matcher matcher = hrefPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ if (lastURL != null)
+ {
+ lastElementIsLink = true;
+ }
+ } catch (Exception e) {}
+ break;
+ }
+ else if (token.equalsIgnoreCase("rel"))
+ {
+ if (tokenizer.hasMoreTokens())
+ {
+ String relType = tokenizer.nextToken();
+ if (relType.equalsIgnoreCase("stylesheet"))
+ {
+ isStyleSheet = true;
}
+ }
}
+ }
- String[] urlArray = new String[associatedFiles.size()];
- associatedFiles.toArray(urlArray);
- return urlArray;
+ if (lastURL != null)
+ {
+ if (isStyleSheet)
+ {
+ lastElementIsAssociatedFile = true;
+ }
+ else
+ {
+ lastElementIsLink = true;
+ }
+ }
}
-
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that are in the form of links to other content.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that are in the form of links to other content, or
- * <CODE>null</CODE> if a problem occurs while trying to parse the
- * HTML.
- */
- public String[] getDocumentLinks() {
- if (!parsed) {
- if (!parse()) {
- return null;
- }
+ else if (lowerToken.equals("script"))
+ {
+ while (tokenizer.hasMoreTokens())
+ {
+ token = tokenizer.nextToken();
+ if (token.equalsIgnoreCase("src"))
+ {
+ try
+ {
+ Matcher matcher = srcPattern.matcher(tag);
+ String uri = matcher.replaceAll("$1");
+ lastURL = uriToURL(uri);
+ } catch (Exception e) {}
+ break;
+ }
+ }
+
+ if (lastURL == null)
+ {
+ int endScriptPos = lowerData.indexOf("</script>", lastElementEndPos+1);
+ if (endScriptPos > 0)
+ {
+ lastElementEndPos = endScriptPos + 8;
+ tag = htmlData.substring(lastElementStartPos, lastElementEndPos+1);
+ lastElementIsChunk = true;
}
+ }
+ else
+ {
+ lastElementIsAssociatedFile = true;
+ }
+ }
- String[] urlArray = new String[documentLinks.size()];
- documentLinks.toArray(urlArray);
- return urlArray;
+ return tag;
+ }
+
+
+
+ /**
+ * Converts the provided URI to a URL. The provided URI may be a URL already,
+ * or it may also be an absolute path on the server or a path relative to the
+ * base URL.
+ *
+ * @param uri The URI to convert to a URL.
+ *
+ * @return The URL based on the provided URI.
+ */
+ private String uriToURL(String uri)
+ {
+ String url = null;
+
+ if (uri.indexOf("://") > 0)
+ {
+ if (uri.startsWith("http"))
+ {
+ url = uri;
+ }
+ }
+ else if (uri.startsWith("/"))
+ {
+ url = protocolHostPort + uri;
+ }
+ else
+ {
+ url = baseURL + uri;
}
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference images used in the document.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that reference images used in the document.
- */
- public String[] getDocumentImages() {
- if (!parsed) {
- if (!parse()) {
- return null;
- }
- }
+ return url;
+ }
+
+
+
+ /**
+ * Retrieves the URL of this HTML document.
+ *
+ * @return The URL of this HTML document.
+ */
+ public String getDocumentURL()
+ {
+ return documentURL;
+ }
+
+
+
+ /**
+ * Retrieves the original HTML data used to create this document.
+ *
+ * @return The orginal HTML data used to create this document.
+ */
+ public String getHTMLData()
+ {
+ return htmlData;
+ }
+
+
+
+ /**
+ * Retrieves the contents of the HTML document with all tags removed.
+ *
+ * @return The contents of the HTML document with all tags removed, or
+ * <CODE>null</CODE> if a problem occurs while trying to parse the
+ * HTML.
+ */
+ public String getTextData()
+ {
+ if (! parsed)
+ {
+ if (! parse())
+ {
+ return null;
+ }
+ }
- String[] urlArray = new String[documentImages.size()];
- documentImages.toArray(urlArray);
- return urlArray;
+ return textData.toString();
+ }
+
+
+
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference files that would normally be downloaded as part of
+ * retrieving a page in a browser. This includes images and external style
+ * sheets.
+ *
+ * @return An array containing a set of URLs to files associated with the
+ * HTML document, or <CODE>null</CODE> if a problem occurs while
+ * trying to parse the HTML.
+ */
+ public String[] getAssociatedFiles()
+ {
+ if (! parsed)
+ {
+ if (! parse())
+ {
+ return null;
+ }
}
- /**
- * Retrieves an array containing a set of URLs parsed from the HTML document
- * that reference frames used in the document.
- *
- * @return An array containing a set of URLs parsed from the HTML document
- * that reference frames used in the document.
- */
- public String[] getDocumentFrames() {
- if (!parsed) {
- if (!parse()) {
- return null;
- }
- }
+ String[] urlArray = new String[associatedFiles.size()];
+ associatedFiles.toArray(urlArray);
+ return urlArray;
+ }
+
+
+
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that are in the form of links to other content.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that are in the form of links to other content, or
+ * <CODE>null</CODE> if a problem occurs while trying to parse the
+ * HTML.
+ */
+ public String[] getDocumentLinks()
+ {
+ if (! parsed)
+ {
+ if (! parse())
+ {
+ return null;
+ }
+ }
- String[] urlArray = new String[documentFrames.size()];
- documentFrames.toArray(urlArray);
- return urlArray;
+ String[] urlArray = new String[documentLinks.size()];
+ documentLinks.toArray(urlArray);
+ return urlArray;
+ }
+
+
+
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference images used in the document.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that reference images used in the document.
+ */
+ public String[] getDocumentImages()
+ {
+ if (! parsed)
+ {
+ if (! parse())
+ {
+ return null;
+ }
}
+
+ String[] urlArray = new String[documentImages.size()];
+ documentImages.toArray(urlArray);
+ return urlArray;
+ }
+
+
+
+ /**
+ * Retrieves an array containing a set of URLs parsed from the HTML document
+ * that reference frames used in the document.
+ *
+ * @return An array containing a set of URLs parsed from the HTML document
+ * that reference frames used in the document.
+ */
+ public String[] getDocumentFrames()
+ {
+ if (! parsed)
+ {
+ if (! parse())
+ {
+ return null;
+ }
+ }
+
+ String[] urlArray = new String[documentFrames.size()];
+ documentFrames.toArray(urlArray);
+ return urlArray;
+ }
}
+
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
index 0ab1a639..066fb0b4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.http;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -43,1201 +42,1367 @@ import com.netscape.pkisilent.argparser.ArgParser;
import com.netscape.pkisilent.argparser.StringHolder;
import com.netscape.pkisilent.common.ComCrypto;
-public class HTTPClient implements SSLCertificateApprovalCallback {
-
- public static final int BUFFER_SIZE = 4096;
- public boolean debugMode = true;
-
- public static String basic_auth_header_value = null;
-
- public static String cs_hostname = null;
- public static String cs_port = null;
- public static String ssl = null;
- public static String client_certdb_dir = null;
- public static String client_certdb_pwd = null;
- public static String client_cert_nickname = null;
- public static String uri = null;
- public static String query = null;
- public static String request_type = null;
- public static String user_id = null;
- public static String user_password = null;
- public static String auth_type = null;
- public static String debug = null;
-
- public static boolean parse_xml = false;
- public static X509Certificate server_cert = null;
-
- // cookie variable for CS install UI
- public static String j_session_id = null;
- public static boolean ecc_support = false;
-
- public HTTPClient() {
- // constructor
- // turn off ecc by default
- ecc_support = true;
- }
-
- public HTTPClient(boolean ecc) {
- ecc_support = ecc;
- }
-
- public boolean setCipherPref(SSLSocket socket) {
-
- if (ecc_support) {
- int ecc_Ciphers[] = { SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
- SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 0 };
-
- try {
- for (int i = 0; i < ecc_Ciphers.length; i++) {
- if (ecc_Ciphers[i] > 0)
- socket.setCipherPreference(ecc_Ciphers[i], true);
- }
- } catch (Exception e) {
- System.out.println("ERROR: unable to set ECC Cipher List");
- System.out.println("ERROR: Exception = " + e.getMessage());
- }
-
- }
- return true;
- }
-
- public boolean disableSSL2(SSLSocket socket) {
- try {
- SSLSocket.enableSSL3Default(true);
- socket.enableSSL3(true);
- socket.enableSSL2(false);
- SSLSocket.enableSSL2Default(false);
+public class HTTPClient implements SSLCertificateApprovalCallback
+{
+
+ public static final int BUFFER_SIZE = 4096;
+ public boolean debugMode = true;
+
+ public static String basic_auth_header_value = null;
+
+ public static String cs_hostname = null;
+ public static String cs_port = null;
+ public static String ssl = null;
+ public static String client_certdb_dir = null;
+ public static String client_certdb_pwd = null;
+ public static String client_cert_nickname = null;
+ public static String uri = null;
+ public static String query = null;
+ public static String request_type = null;
+ public static String user_id = null;
+ public static String user_password = null;
+ public static String auth_type = null;
+ public static String debug = null;
+
+ public static boolean parse_xml = false;
+
+ public static X509Certificate server_cert = null;
+
+ // cookie variable for CS install UI
+ public static String j_session_id = null;
+ public static boolean ecc_support = false;
+
+
+
+
+ public HTTPClient()
+ {
+ // constructor
+ // turn off ecc by default
+ ecc_support = true;
+ }
+
+
+ public HTTPClient(boolean ecc)
+ {
+ ecc_support = ecc;
+ }
+
+ public boolean setCipherPref(SSLSocket socket)
+ {
+
+ if(ecc_support)
+ {
+ int ecc_Ciphers[] = {
+ SSLSocket.TLS_ECDH_ECDSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ SSLSocket.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ SSLSocket.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ SSLSocket.TLS_ECDH_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSLSocket.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_NULL_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ SSLSocket.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ 0 };
+
+ try
+ {
+ for (int i=0; i < ecc_Ciphers.length; i++)
+ {
+ if(ecc_Ciphers[i] > 0)
+ socket.setCipherPreference(
+ ecc_Ciphers[i],true);
+ }
+ }
+ catch(Exception e)
+ {
+ System.out.println("ERROR: unable to set ECC Cipher List");
+ System.out.println("ERROR: Exception = " + e.getMessage());
+ }
+
+ }
+ return true;
+ }
+
+ public boolean disableSSL2(SSLSocket socket)
+ {
+ try
+ {
+ SSLSocket.enableSSL3Default(true);
+ socket.enableSSL3(true);
+ socket.enableSSL2(false);
+ SSLSocket.enableSSL2Default(false);
socket.enableV2CompatibleHello(false);
- } catch (Exception e) {
- System.out.println("ERROR: Exception = " + e.getMessage());
- }
- return true;
- }
-
- public X509Certificate getServerCert() {
- return server_cert;
+ }
+ catch(Exception e)
+ {
+ System.out.println("ERROR: Exception = " + e.getMessage());
+ }
+ return true;
+ }
+
+ public X509Certificate getServerCert()
+ {
+ return server_cert;
+ }
+
+ public void set_parse_xml(boolean b)
+ {
+ parse_xml = b;
+ }
+
+ public boolean approve(X509Certificate cert,
+ SSLCertificateApprovalCallback.ValidityStatus status)
+ {
+
+ // when this method is called by SSLSocket we get the server cert
+ // we can capture this for future use.
+ server_cert = cert;
+ return true;
+ }
+
+ public boolean testsslConnect(String hostname, String portnumber)
+ {
+ boolean st = true;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, this,
+ certSelectionCallback );
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ // test connection to obtain server cert. close it.
+ socket.close();
+
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return false;
+ else
+ return true;
+ }
+
+ // performs ssl connect to given host/port requiring client auth
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse sslConnectClientAuth(String hostname, String portnumber,
+ String client_cert,String url,String query)
+ {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ CertSelection certSelectionCallback =
+ new CertSelection();
+
+ // Client Cert for Auth is set here
+ certSelectionCallback.setClientCert(client_cert);
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback );
+ disableSSL2(socket);
+ setCipherPref(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ System.out.println("Posting Query = " +
+ "https://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+ ps.println("POST " + url + " HTTP/1.0");
+ ps.println("Connection: Keep-Alive");
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " +query.length());
+ ps.println("");
+ ps.print(query);
+ ps.flush();
+ os.flush();
+
+ try
+ {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os=null;
+ rawos=null;
+ ps=null;
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return null;
+ else
+ return hr;
+ }
+
+ // performs ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse sslConnect(String hostname, String portnumber,
+ String url, String query)
+ {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback );
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ System.out.println("Posting Query = " +
+ "https://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+
+ ps.println("POST " + url + " HTTP/1.0");
+
+ // check to see if we have a cookie to send
+ if(j_session_id != null )
+ ps.println("Cookie: " + j_session_id);
+
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " +query.length());
+ ps.println("Connection: Keep-Alive");
+
+ // special header posting if available
+ if(basic_auth_header_value != null)
+ {
+ System.out.println("basic_auth = " + basic_auth_header_value );
+ ps.println("Authorization: Basic " + basic_auth_header_value );
+ }
+
+ ps.println("");
+ ps.println(query);
+ ps.println("\r");
+ ps.flush();
+ os.flush();
+
+ try
+ {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os=null;
+ rawos=null;
+ ps=null;
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return null;
+ else
+ return hr;
+ }
+
+ // performs non ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse nonsslConnect(String hostname, String portnumber,
+ String url, String query)
+ {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ Socket socket = new Socket(hostname, port);
+
+ System.out.println("Posting Query = " +
+ "http://" + hostname +
+ ":" + portnumber +
+ "/" + url +
+ "?" + query);
+
+ OutputStream rawos = socket.getOutputStream();
+ BufferedOutputStream os = new BufferedOutputStream(rawos);
+ PrintStream ps = new PrintStream(os);
+
+ System.out.println("Connected.");
+
+ ps.println("POST " + url + " HTTP/1.0");
+
+ // check to see if we have a cookie to send
+ if(j_session_id != null )
+ ps.println("Cookie: " + j_session_id);
+
+ ps.println("Content-type: application/x-www-form-urlencoded");
+ ps.println("Content-length: " +query.length());
+ ps.println("Connection: Keep-Alive");
+
+ // special header posting if available
+ if(basic_auth_header_value != null)
+ {
+ System.out.println("basic_auth = " + basic_auth_header_value );
+ ps.println("Authorization: Basic " + basic_auth_header_value );
+ }
+
+ ps.println("");
+ ps.println(query);
+ ps.println("\r");
+ ps.flush();
+ os.flush();
+
+ try
+ {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ os.close();
+ rawos.close();
+ ps.close();
+
+ os=null;
+ rawos=null;
+ ps=null;
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return null;
+ else
+ return hr;
+ }
+
+ public HTTPResponse readResponse(InputStream inputStream)
+ throws Exception
+ {
+ // read response from http input stream and return HTTPResponse
+ byte[] buffer = new byte[BUFFER_SIZE];
+ HTTPResponse response = null;
+ int statusCode = 0;
+
+ // Read an initial chunk of the response from the server.
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0)
+ {
+ throw new IOException("Unexpected end of input stream from server");
}
- public void set_parse_xml(boolean b) {
- parse_xml = b;
+ // Hopefully, this initial chunk will contain the entire header, so look for
+ // it. Technically, HTTP is supposed to use CRLF as the end-of-line
+ // character, so look for that first, but also check for LF by itself just
+ // in case.
+ int headerEndPos = -1;
+ int dataStartPos = -1;
+ for (int i=0; i < (bytesRead-3); i++)
+ {
+ if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
+ (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+4;
+ break;
+ }
}
- public boolean approve(X509Certificate cert,
- SSLCertificateApprovalCallback.ValidityStatus status) {
-
- // when this method is called by SSLSocket we get the server cert
- // we can capture this for future use.
- server_cert = cert;
- return true;
- }
-
- public boolean testsslConnect(String hostname, String portnumber) {
- boolean st = true;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- SSLClientCertificateSelectionCallback certSelectionCallback = new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, this,
- certSelectionCallback);
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- // test connection to obtain server cert. close it.
- socket.close();
-
+ if (headerEndPos < 0)
+ {
+ for (int i=0; i < (bytesRead-1); i++)
+ {
+ if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+2;
+ break;
}
-
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
- }
-
- if (!st)
- return false;
- else
- return true;
+ }
}
- // performs ssl connect to given host/port requiring client auth
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse sslConnectClientAuth(String hostname,
- String portnumber, String client_cert, String url, String query) {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- SSLCertificateApprovalCallback approvalCallback = new TestCertApprovalCallback();
- CertSelection certSelectionCallback = new CertSelection();
-
- // Client Cert for Auth is set here
- certSelectionCallback.setClientCert(client_cert);
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback);
- disableSSL2(socket);
- setCipherPref(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- System.out.println("Posting Query = " + "https://" + hostname + ":"
- + portnumber + "/" + url + "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
- ps.println("POST " + url + " HTTP/1.0");
- ps.println("Connection: Keep-Alive");
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " + query.length());
- ps.println("");
- ps.print(query);
- ps.flush();
- os.flush();
-
- try {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- } catch (Exception e) {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os = null;
- rawos = null;
- ps = null;
+ // In the event that we didn't get the entire header in the first pass, keep
+ // reading until we do have enough.
+ if (headerEndPos < 0)
+ {
+ byte[] buffer2 = new byte[BUFFER_SIZE];
+ while (headerEndPos < 0)
+ {
+ int startPos = bytesRead;
+ int moreBytesRead = inputStream.read(buffer2);
+ if (moreBytesRead < 0)
+ {
+ throw new IOException("Unexpected end of input stream from server " +
+ "when reading more data from response");
}
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
+ byte[] newBuffer = new byte[bytesRead + moreBytesRead];
+ System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
+ System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
+ buffer = newBuffer;
+ bytesRead += moreBytesRead;
+
+ for (int i=startPos; i < (bytesRead-3); i++)
+ {
+ if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
+ (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+4;
+ break;
+ }
}
- if (!st)
- return null;
- else
- return hr;
- }
-
- // performs ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse sslConnect(String hostname, String portnumber,
- String url, String query) {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- SSLCertificateApprovalCallback approvalCallback = new TestCertApprovalCallback();
- SSLClientCertificateSelectionCallback certSelectionCallback = new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback);
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- System.out.println("Posting Query = " + "https://" + hostname + ":"
- + portnumber + "/" + url + "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
- ps.println("POST " + url + " HTTP/1.0");
-
- // check to see if we have a cookie to send
- if (j_session_id != null)
- ps.println("Cookie: " + j_session_id);
-
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " + query.length());
- ps.println("Connection: Keep-Alive");
-
- // special header posting if available
- if (basic_auth_header_value != null) {
- System.out.println("basic_auth = " + basic_auth_header_value);
- ps.println("Authorization: Basic " + basic_auth_header_value);
+ if (headerEndPos < 0)
+ {
+ for (int i=startPos; i < (bytesRead-1); i++)
+ {
+ if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+2;
+ break;
}
-
- ps.println("");
- ps.println(query);
- ps.println("\r");
- ps.flush();
- os.flush();
-
- try {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- } catch (Exception e) {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os = null;
- rawos = null;
- ps = null;
-
- }
-
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
+ }
}
-
- if (!st)
- return null;
- else
- return hr;
+ }
}
- // performs non ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse nonsslConnect(String hostname, String portnumber,
- String url, String query) {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- Socket socket = new Socket(hostname, port);
-
- System.out.println("Posting Query = " + "http://" + hostname + ":"
- + portnumber + "/" + url + "?" + query);
-
- OutputStream rawos = socket.getOutputStream();
- BufferedOutputStream os = new BufferedOutputStream(rawos);
- PrintStream ps = new PrintStream(os);
-
- System.out.println("Connected.");
-
- ps.println("POST " + url + " HTTP/1.0");
-
- // check to see if we have a cookie to send
- if (j_session_id != null)
- ps.println("Cookie: " + j_session_id);
-
- ps.println("Content-type: application/x-www-form-urlencoded");
- ps.println("Content-length: " + query.length());
- ps.println("Connection: Keep-Alive");
-
- // special header posting if available
- if (basic_auth_header_value != null) {
- System.out.println("basic_auth = " + basic_auth_header_value);
- ps.println("Authorization: Basic " + basic_auth_header_value);
- }
-
- ps.println("");
- ps.println(query);
- ps.println("\r");
- ps.flush();
- os.flush();
- try {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
-
- } catch (Exception e) {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- os.close();
- rawos.close();
- ps.close();
-
- os = null;
- rawos = null;
- ps = null;
-
- }
-
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
- }
-
- if (!st)
- return null;
- else
- return hr;
- }
-
- public HTTPResponse readResponse(InputStream inputStream) throws Exception {
- // read response from http input stream and return HTTPResponse
- byte[] buffer = new byte[BUFFER_SIZE];
- HTTPResponse response = null;
- int statusCode = 0;
-
- // Read an initial chunk of the response from the server.
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0) {
- throw new IOException("Unexpected end of input stream from server");
- }
-
- // Hopefully, this initial chunk will contain the entire header, so look
- // for
- // it. Technically, HTTP is supposed to use CRLF as the end-of-line
- // character, so look for that first, but also check for LF by itself
- // just
- // in case.
- int headerEndPos = -1;
- int dataStartPos = -1;
- for (int i = 0; i < (bytesRead - 3); i++) {
- if ((buffer[i] == '\r') && (buffer[i + 1] == '\n')
- && (buffer[i + 2] == '\r') && (buffer[i + 3] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 4;
- break;
- }
- }
-
- if (headerEndPos < 0) {
- for (int i = 0; i < (bytesRead - 1); i++) {
- if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 2;
- break;
- }
- }
+ // At this point, we should have the entire header, so read and analyze it.
+ String headerStr = new String(buffer, 0, headerEndPos);
+ StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n");
+ if (tokenizer.hasMoreTokens())
+ {
+ String statusLine = tokenizer.nextToken();
+ if (debugMode)
+ {
+ System.out.println("RESPONSE STATUS: " + statusLine);
+ }
+
+ int spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0)
+ {
+ System.out.println("ERROR: Unable to parse response header -- could " +
+ "not find protocol/version delimiter");
+ return null;
+
+ }
+
+ String protocolVersion = statusLine.substring(0, spacePos);
+ int spacePos2 = statusLine.indexOf(' ', spacePos+1);
+ if (spacePos2 < 0)
+ {
+ System.out.println("ERROR: Unable to parse response header -- could " +
+ "not find response code delimiter");
+ return null;
+ }
+
+ try
+ {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ spacePos2));
+ }
+ catch (NumberFormatException nfe)
+ {
+ System.out.println("Unable to parse response header -- could " +
+ "not interpret status code as an integer");
+ return null;
+ }
+
+ String responseMessage = statusLine.substring(spacePos2+1);
+ response = new HTTPResponse(statusCode, protocolVersion,
+ responseMessage);
+
+ while (tokenizer.hasMoreTokens())
+ {
+ String headerLine = tokenizer.nextToken();
+ if (debugMode)
+ {
+ System.out.println("RESPONSE HEADER: " + headerLine);
}
- // In the event that we didn't get the entire header in the first pass,
- // keep
- // reading until we do have enough.
- if (headerEndPos < 0) {
- byte[] buffer2 = new byte[BUFFER_SIZE];
- while (headerEndPos < 0) {
- int startPos = bytesRead;
- int moreBytesRead = inputStream.read(buffer2);
- if (moreBytesRead < 0) {
- throw new IOException(
- "Unexpected end of input stream from server "
- + "when reading more data from response");
- }
-
- byte[] newBuffer = new byte[bytesRead + moreBytesRead];
- System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
- System.arraycopy(buffer2, 0, newBuffer, bytesRead,
- moreBytesRead);
- buffer = newBuffer;
- bytesRead += moreBytesRead;
-
- for (int i = startPos; i < (bytesRead - 3); i++) {
- if ((buffer[i] == '\r') && (buffer[i + 1] == '\n')
- && (buffer[i + 2] == '\r')
- && (buffer[i + 3] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 4;
- break;
- }
- }
-
- if (headerEndPos < 0) {
- for (int i = startPos; i < (bytesRead - 1); i++) {
- if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 2;
- break;
- }
- }
- }
+ int colonPos = headerLine.indexOf(':');
+ if (colonPos < 0)
+ {
+ if (headerLine.toLowerCase().startsWith("http/"))
+ {
+ // This is a direct violation of RFC 2616, but certain HTTP servers
+ // seem to immediately follow a 100 continue with a 200 ok without
+ // the required CRLF in between.
+ System.out.println("ERROR: Found illegal status line '" + headerLine +
+ "'in the middle of a response -- attempting " +
+ "to deal with it as the start of a new " +
+ "response.");
+ statusLine = headerLine;
+ spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0)
+ {
+ System.out.println("ERROR: Unable to parse response header -- " +
+ "could not find protocol/version " +
+ "delimiter");
+ return null;
}
- }
-
- // At this point, we should have the entire header, so read and analyze
- // it.
- String headerStr = new String(buffer, 0, headerEndPos);
- StringTokenizer tokenizer = new StringTokenizer(headerStr, "\r\n");
- if (tokenizer.hasMoreTokens()) {
- String statusLine = tokenizer.nextToken();
- if (debugMode) {
- System.out.println("RESPONSE STATUS: " + statusLine);
- }
-
- int spacePos = statusLine.indexOf(' ');
- if (spacePos < 0) {
- System.out
- .println("ERROR: Unable to parse response header -- could "
- + "not find protocol/version delimiter");
- return null;
+ protocolVersion = statusLine.substring(0, spacePos);
+ spacePos2 = statusLine.indexOf(' ', spacePos+1);
+ if (spacePos2 < 0)
+ {
+ System.out.println("ERROR: Unable to parse response header -- " +
+ "could not find response code delimiter");
+ return null;
}
- String protocolVersion = statusLine.substring(0, spacePos);
- int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
- if (spacePos2 < 0) {
- System.out
- .println("ERROR: Unable to parse response header -- could "
- + "not find response code delimiter");
- return null;
+ try
+ {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ spacePos2));
}
-
- try {
- statusCode = Integer.parseInt(statusLine.substring(
- spacePos + 1, spacePos2));
- } catch (NumberFormatException nfe) {
- System.out.println("Unable to parse response header -- could "
- + "not interpret status code as an integer");
- return null;
+ catch (NumberFormatException nfe)
+ {
+ System.out.println("ERROR: Unable to parse response header -- " +
+ "could not interpret status code as an " +
+ "integer");
+ return null;
}
- String responseMessage = statusLine.substring(spacePos2 + 1);
+ responseMessage = statusLine.substring(spacePos2+1);
response = new HTTPResponse(statusCode, protocolVersion,
- responseMessage);
-
- while (tokenizer.hasMoreTokens()) {
- String headerLine = tokenizer.nextToken();
- if (debugMode) {
- System.out.println("RESPONSE HEADER: " + headerLine);
- }
-
- int colonPos = headerLine.indexOf(':');
- if (colonPos < 0) {
- if (headerLine.toLowerCase().startsWith("http/")) {
- // This is a direct violation of RFC 2616, but certain
- // HTTP servers
- // seem to immediately follow a 100 continue with a 200
- // ok without
- // the required CRLF in between.
- System.out.println("ERROR: Found illegal status line '"
- + headerLine
- + "'in the middle of a response -- attempting "
- + "to deal with it as the start of a new "
- + "response.");
- statusLine = headerLine;
- spacePos = statusLine.indexOf(' ');
- if (spacePos < 0) {
- System.out
- .println("ERROR: Unable to parse response header -- "
- + "could not find protocol/version "
- + "delimiter");
- return null;
- }
-
- protocolVersion = statusLine.substring(0, spacePos);
- spacePos2 = statusLine.indexOf(' ', spacePos + 1);
- if (spacePos2 < 0) {
- System.out
- .println("ERROR: Unable to parse response header -- "
- + "could not find response code delimiter");
- return null;
- }
-
- try {
- statusCode = Integer.parseInt(statusLine.substring(
- spacePos + 1, spacePos2));
- } catch (NumberFormatException nfe) {
- System.out
- .println("ERROR: Unable to parse response header -- "
- + "could not interpret status code as an "
- + "integer");
- return null;
- }
-
- responseMessage = statusLine.substring(spacePos2 + 1);
- response = new HTTPResponse(statusCode,
- protocolVersion, responseMessage);
- continue;
- } else {
- System.out
- .println("ERROR: Unable to parse response header -- no "
- + "colon found on header line \""
- + headerLine + "\"");
- }
- }
-
- String headerName = headerLine.substring(0, colonPos);
- String headerValue = headerLine.substring(colonPos + 1).trim();
- response.addHeader(headerName, headerValue);
- }
- } else {
- // This should never happen -- an empty response
- System.out.println("Unable to parse response header -- empty "
- + "header");
+ responseMessage);
+ continue;
+ }
+ else
+ {
+ System.out.println("ERROR: Unable to parse response header -- no " +
+ "colon found on header line \"" +
+ headerLine + "\"");
+ }
}
- // If the status code was 100 (continue), then it was an intermediate
- // header
- // and we need to keep reading until we get the real response header.
- while (response.getStatusCode() == 100) {
- if (dataStartPos < bytesRead) {
- byte[] newBuffer = new byte[bytesRead - dataStartPos];
- System.arraycopy(buffer, dataStartPos, newBuffer, 0,
- newBuffer.length);
- buffer = newBuffer;
- bytesRead = buffer.length;
-
- headerEndPos = -1;
- for (int i = 0; i < (bytesRead - 3); i++) {
- if ((buffer[i] == '\r') && (buffer[i + 1] == '\n')
- && (buffer[i + 2] == '\r')
- && (buffer[i + 3] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 4;
- break;
- }
- }
-
- if (headerEndPos < 0) {
- for (int i = 0; i < (bytesRead - 1); i++) {
- if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 2;
- break;
- }
- }
- }
- } else {
- buffer = new byte[0];
- bytesRead = 0;
- headerEndPos = -1;
- }
+ String headerName = headerLine.substring(0, colonPos);
+ String headerValue = headerLine.substring(colonPos+1).trim();
+ response.addHeader(headerName, headerValue);
+ }
+ }
+ else
+ {
+ // This should never happen -- an empty response
+ System.out.println("Unable to parse response header -- empty " +
+ "header");
+ }
- byte[] buffer2 = new byte[BUFFER_SIZE];
- while (headerEndPos < 0) {
- int startPos = bytesRead;
- int moreBytesRead = inputStream.read(buffer2);
-
- if (moreBytesRead < 0) {
- throw new IOException(
- "Unexpected end of input stream from server "
- + "when reading more data from response");
- }
-
- byte[] newBuffer = new byte[bytesRead + moreBytesRead];
- System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
- System.arraycopy(buffer2, 0, newBuffer, bytesRead,
- moreBytesRead);
- buffer = newBuffer;
- bytesRead += moreBytesRead;
-
- for (int i = startPos; i < (bytesRead - 3); i++) {
- if ((buffer[i] == '\r') && (buffer[i + 1] == '\n')
- && (buffer[i + 2] == '\r')
- && (buffer[i + 3] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 4;
- break;
- }
- }
-
- if (headerEndPos < 0) {
- for (int i = startPos; i < (bytesRead - 1); i++) {
- if ((buffer[i] == '\n') && (buffer[i + 1] == '\n')) {
- headerEndPos = i;
- dataStartPos = i + 2;
- break;
- }
- }
- }
- }
- // We should now have the next header, so examine it.
- headerStr = new String(buffer, 0, headerEndPos);
- tokenizer = new StringTokenizer(headerStr, "\r\n");
- if (tokenizer.hasMoreTokens()) {
- String statusLine = tokenizer.nextToken();
- if (debugMode) {
- System.out.println("RESPONSE STATUS: " + statusLine);
- }
-
- int spacePos = statusLine.indexOf(' ');
- if (spacePos < 0) {
- System.out
- .println("Unable to parse response header -- could "
- + "not find protocol/version delimiter");
- }
-
- String protocolVersion = statusLine.substring(0, spacePos);
- int spacePos2 = statusLine.indexOf(' ', spacePos + 1);
- if (spacePos2 < 0) {
- System.out
- .println("Unable to parse response header -- could "
- + "not find response code delimiter");
- }
-
- try {
- statusCode = Integer.parseInt(statusLine.substring(
- spacePos + 1, spacePos2));
- } catch (NumberFormatException nfe) {
- System.out
- .println("Unable to parse response header -- could "
- + "not interpret status code as an integer");
- }
-
- String responseMessage = statusLine.substring(spacePos2 + 1);
- response = new HTTPResponse(statusCode, protocolVersion,
- responseMessage);
-
- while (tokenizer.hasMoreTokens()) {
- String headerLine = tokenizer.nextToken();
- if (debugMode) {
- System.out.println("RESPONSE HEADER: " + headerLine);
- }
-
- int colonPos = headerLine.indexOf(':');
- if (colonPos < 0) {
- System.out
- .println("Unable to parse response header -- no "
- + "colon found on header line \""
- + headerLine + "\"");
- }
-
- String headerName = headerLine.substring(0, colonPos);
- String headerValue = headerLine.substring(colonPos + 1)
- .trim();
- response.addHeader(headerName, headerValue);
- }
- } else {
- // This should never happen -- an empty response
- System.out.println("Unable to parse response header -- empty "
- + "header");
- }
+ // If the status code was 100 (continue), then it was an intermediate header
+ // and we need to keep reading until we get the real response header.
+ while (response.getStatusCode() == 100)
+ {
+ if (dataStartPos < bytesRead)
+ {
+ byte[] newBuffer = new byte[bytesRead - dataStartPos];
+ System.arraycopy(buffer, dataStartPos, newBuffer, 0, newBuffer.length);
+ buffer = newBuffer;
+ bytesRead = buffer.length;
+
+ headerEndPos = -1;
+ for (int i=0; i < (bytesRead-3); i++)
+ {
+ if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
+ (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+4;
+ break;
+ }
}
- // Now that we have parsed the header, use it to determine how much data
- // there is. If we're lucky, the server will have told us using the
- // "Content-Length" header.
- int contentLength = response.getContentLength();
-
- if (contentLength >= 0) {
- readContentDataUsingLength(response, inputStream, contentLength,
- buffer, dataStartPos, bytesRead);
- } else {
- // It's not chunked encoding, so our last hope is that the
- // connection
- // will be closed when all the data has been sent.
- String connectionStr = response.getHeader("connection");
- if ((connectionStr != null)
- && (!connectionStr.equalsIgnoreCase("close"))) {
- System.out
- .println("ERROR:Unable to determine how to find when the "
- + "end of the data has been reached (no "
- + "content length, not chunked encoding, "
- + "connection string is \""
- + connectionStr
- + "\" rather than \"close\")");
- } else {
- readContentDataUsingConnectionClose(response, inputStream,
- buffer, dataStartPos, bytesRead);
+ if (headerEndPos < 0)
+ {
+ for (int i=0; i < (bytesRead-1); i++)
+ {
+ if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+2;
+ break;
}
+ }
}
- // Finally, return the response to the caller.
- return response;
- }
-
- /**
- * Reads the actual data of the response based on the content length
- * provided by the server in the response header.
- *
- * @param response The response with which the data is associated.
- * @param inputStream The input stream from which to read the response.
- * @param contentLength The number of bytes that the server said are in the
- * response.
- * @param dataRead The data that we have already read. This includes the
- * header data, but may also include some or all of the content
- * data as well.
- * @param dataStartPos The position in the provided array at which the
- * content data starts.
- * @param dataBytesRead The total number of valid bytes in the provided
- * array that should be considered part of the response (the
- * number of header bytes is included in this count).
- *
- * @throws IOException If a problem occurs while reading data from the
- * server.
- */
- private void readContentDataUsingLength(HTTPResponse response,
- InputStream inputStream, int contentLength, byte[] dataRead,
- int dataStartPos, int dataBytesRead) throws IOException {
- if (contentLength <= 0) {
- response.setResponseData(new byte[0]);
- return;
+ }
+ else
+ {
+ buffer = new byte[0];
+ bytesRead = 0;
+ headerEndPos = -1;
+ }
+
+
+ byte[] buffer2 = new byte[BUFFER_SIZE];
+ while (headerEndPos < 0)
+ {
+ int startPos = bytesRead;
+ int moreBytesRead = inputStream.read(buffer2);
+
+ if (moreBytesRead < 0)
+ {
+ throw new IOException("Unexpected end of input stream from server " +
+ "when reading more data from response");
}
- byte[] contentBytes = new byte[contentLength];
- int startPos = 0;
- if (dataBytesRead > dataStartPos) {
- // We've already got some data to include in the header, so copy
- // that into
- // the content array. Make sure the server didn't do something
- // stupid
- // like return more data than it told us was in the response.
- int bytesToCopy = Math.min(contentBytes.length,
- (dataBytesRead - dataStartPos));
- System.arraycopy(dataRead, dataStartPos, contentBytes, 0,
- bytesToCopy);
- startPos = bytesToCopy;
+ byte[] newBuffer = new byte[bytesRead + moreBytesRead];
+ System.arraycopy(buffer, 0, newBuffer, 0, bytesRead);
+ System.arraycopy(buffer2, 0, newBuffer, bytesRead, moreBytesRead);
+ buffer = newBuffer;
+ bytesRead += moreBytesRead;
+
+ for (int i=startPos; i < (bytesRead-3); i++)
+ {
+ if ((buffer[i] == '\r') && (buffer[i+1] == '\n') &&
+ (buffer[i+2] == '\r') && (buffer[i+3] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+4;
+ break;
+ }
}
- byte[] buffer = new byte[BUFFER_SIZE];
- while (startPos < contentBytes.length) {
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0) {
- throw new IOException(
- "Unexpected end of input stream reached when "
- + "reading data from the server");
+ if (headerEndPos < 0)
+ {
+ for (int i=startPos; i < (bytesRead-1); i++)
+ {
+ if ((buffer[i] == '\n') && (buffer[i+1] == '\n'))
+ {
+ headerEndPos = i;
+ dataStartPos = i+2;
+ break;
}
-
- System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
- startPos += bytesRead;
+ }
}
-
- response.setResponseData(contentBytes);
- }
-
- /**
- * Reads the actual data of the response using chunked encoding, which is a
- * way for the server to provide the data in several chunks rather than all
- * at once.
- *
- * @param response The response with which the data is associated.
- * @param inputStream The input stream from which to read the response.
- * @param dataRead The data that we have already read. This includes the
- * header data, but may also include some or all of the content
- * data as well.
- * @param dataStartPos The position in the provided array at which the
- * content data starts.
- * @param dataBytesRead The total number of valid bytes in the provided
- * array that should be considered part of the response (the
- * number of header bytes is included in this count).
- *
- * @throws IOException If a problem occurs while reading data from the
- * server.
- */
- private void readContentDataUsingConnectionClose(HTTPResponse response,
- InputStream inputStream, byte[] dataRead, int dataStartPos,
- int dataBytesRead) throws IOException {
- // Create an array list that we will use to hold the chunks of
- // information
- // read from the server.
- ArrayList<ByteBuffer> bufferList = new ArrayList<ByteBuffer>();
-
- // Create a variable to hold the total number of bytes in the data.
- int totalBytes = 0;
-
- // See if we have unread data in the array already provided.
- int existingBytes = dataBytesRead - dataStartPos;
- if (existingBytes > 0) {
- ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes);
- byteBuffer.put(dataRead, dataStartPos, existingBytes);
- bufferList.add(byteBuffer);
- totalBytes += existingBytes;
+ }
+
+
+ // We should now have the next header, so examine it.
+ headerStr = new String(buffer, 0, headerEndPos);
+ tokenizer = new StringTokenizer(headerStr, "\r\n");
+ if (tokenizer.hasMoreTokens())
+ {
+ String statusLine = tokenizer.nextToken();
+ if (debugMode)
+ {
+ System.out.println("RESPONSE STATUS: " + statusLine);
}
- // Keep reading until we hit the end of the input stream.
- byte[] buffer = new byte[BUFFER_SIZE];
- while (true) {
- try {
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0) {
- // We've hit the end of the stream and therefore the end of
- // the
- // document.
- break;
- } else if (bytesRead > 0) {
- ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
- byteBuffer.put(buffer, 0, bytesRead);
- bufferList.add(byteBuffer);
- totalBytes += bytesRead;
- }
- } catch (IOException ioe) {
- // In this case we'll assume that the end of the stream has been
- // reached. It's possible that there was some other error, but
- // we can't
- // do anything about it so try to process what we've got so far.
- System.out.println("ERROR: unable to read until end of stream");
- System.out.println("ERROR: " + ioe.getMessage());
- break;
- }
+ int spacePos = statusLine.indexOf(' ');
+ if (spacePos < 0)
+ {
+ System.out.println("Unable to parse response header -- could " +
+ "not find protocol/version delimiter");
}
- // Assemble the contents of all the buffers into a big array and store
- // that
- // array in the response.
- int startPos = 0;
- byte[] contentData = new byte[totalBytes];
- for (int i = 0; i < bufferList.size(); i++) {
- ByteBuffer byteBuffer = (ByteBuffer) bufferList.get(i);
- byteBuffer.flip();
- byteBuffer.get(contentData, startPos, byteBuffer.limit());
- startPos += byteBuffer.limit();
+ String protocolVersion = statusLine.substring(0, spacePos);
+ int spacePos2 = statusLine.indexOf(' ', spacePos+1);
+ if (spacePos2 < 0)
+ {
+ System.out.println("Unable to parse response header -- could " +
+ "not find response code delimiter");
}
- response.setResponseData(contentData);
- }
-
- // performs ssl connect to given host/port
- // posts the given query data - format - a byte array
- // returns HTTPResponse
-
- public HTTPResponse sslConnect(String hostname, String portnumber,
- String url, byte[] data) {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
-
- Integer x = new Integer(portnumber);
- int port = x.intValue();
-
- SSLCertificateApprovalCallback approvalCallback = new TestCertApprovalCallback();
- SSLClientCertificateSelectionCallback certSelectionCallback = new TestClientCertificateSelectionCallback();
-
- Socket js = new Socket(InetAddress.getByName(hostname), port);
- SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
- certSelectionCallback);
- setCipherPref(socket);
- disableSSL2(socket);
- socket.forceHandshake();
- System.out.println("Connected.");
- socket.setUseClientMode(true);
-
- DataOutputStream dos = new DataOutputStream(
- socket.getOutputStream());
- dos.writeBytes("POST /ocsp HTTP/1.0\r\n");
- dos.writeBytes("Content-length: " + data.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(data);
- dos.writeBytes("\r\n");
- dos.flush();
-
- try {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
- } catch (Exception e) {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- dos.close();
+ try
+ {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ spacePos2));
}
-
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
+ catch (NumberFormatException nfe)
+ {
+ System.out.println("Unable to parse response header -- could " +
+ "not interpret status code as an integer");
}
- if (!st)
- return null;
- else
- return hr;
+ String responseMessage = statusLine.substring(spacePos2+1);
+ response = new HTTPResponse(statusCode, protocolVersion,
+ responseMessage);
+
+ while (tokenizer.hasMoreTokens())
+ {
+ String headerLine = tokenizer.nextToken();
+ if (debugMode)
+ {
+ System.out.println("RESPONSE HEADER: " + headerLine);
+ }
+
+ int colonPos = headerLine.indexOf(':');
+ if (colonPos < 0)
+ {
+ System.out.println("Unable to parse response header -- no " +
+ "colon found on header line \"" +
+ headerLine + "\"");
+ }
+
+ String headerName = headerLine.substring(0, colonPos);
+ String headerValue = headerLine.substring(colonPos+1).trim();
+ response.addHeader(headerName, headerValue);
+ }
+ }
+ else
+ {
+ // This should never happen -- an empty response
+ System.out.println("Unable to parse response header -- empty " +
+ "header");
+ }
}
- // performs non ssl connect to given host/port
- // posts the given query data
- // returns HTTPResponse
- public HTTPResponse nonsslConnect(String hostname, String portnumber,
- String url, byte[] data) {
-
- boolean st = true;
- HTTPResponse hr = null;
-
- try {
-
- System.out.println("#############################################");
- System.out.println("Attempting to connect to: " + hostname + ":"
- + portnumber);
- Integer x = new Integer(portnumber);
- int port = x.intValue();
+ // Now that we have parsed the header, use it to determine how much data
+ // there is. If we're lucky, the server will have told us using the
+ // "Content-Length" header.
+ int contentLength = response.getContentLength();
- Socket socket = new Socket(hostname, port);
- System.out.println("Posting Query = " + "http://" + hostname + ":"
- + portnumber + "/" + url);
-
- System.out.println("Connected.");
-
- DataOutputStream dos = new DataOutputStream(
- socket.getOutputStream());
- dos.writeBytes("POST " + url + " HTTP/1.0\r\n");
- dos.writeBytes("Content-length: " + data.length + "\r\n");
- dos.writeBytes("\r\n");
- dos.write(data);
- dos.writeBytes("\r\n");
- dos.flush();
-
- try {
- hr = readResponse(socket.getInputStream());
- hr.parseContent();
- } catch (Exception e) {
- System.out.println("Exception");
- e.printStackTrace();
- st = false;
- }
-
- socket.close();
- dos.close();
-
- }
-
- catch (Exception e) {
- System.err.println("Exception: Unable to Send Request:" + e);
- e.printStackTrace();
- st = false;
+ if (contentLength >= 0)
+ {
+ readContentDataUsingLength(response, inputStream, contentLength, buffer,
+ dataStartPos, bytesRead);
+ }
+ else
+ {
+ // It's not chunked encoding, so our last hope is that the connection
+ // will be closed when all the data has been sent.
+ String connectionStr = response.getHeader("connection");
+ if ((connectionStr != null) &&
+ (! connectionStr.equalsIgnoreCase("close")))
+ {
+ System.out.println("ERROR:Unable to determine how to find when the " +
+ "end of the data has been reached (no " +
+ "content length, not chunked encoding, " +
+ "connection string is \"" + connectionStr +
+ "\" rather than \"close\")");
}
-
- if (!st)
- return null;
else
- return hr;
+ {
+ readContentDataUsingConnectionClose(response, inputStream, buffer,
+ dataStartPos, bytesRead);
+ }
+ }
+ // Finally, return the response to the caller.
+ return response;
+ }
+
+ /**
+ * Reads the actual data of the response based on the content length provided
+ * by the server in the response header.
+ *
+ * @param response The response with which the data is associated.
+ * @param inputStream The input stream from which to read the response.
+ * @param contentLength The number of bytes that the server said are in the
+ * response.
+ * @param dataRead The data that we have already read. This includes
+ * the header data, but may also include some or all of
+ * the content data as well.
+ * @param dataStartPos The position in the provided array at which the
+ * content data starts.
+ * @param dataBytesRead The total number of valid bytes in the provided
+ * array that should be considered part of the
+ * response (the number of header bytes is included in
+ * this count).
+ *
+ * @throws IOException If a problem occurs while reading data from the
+ * server.
+ */
+ private void readContentDataUsingLength(HTTPResponse response,
+ InputStream inputStream,
+ int contentLength, byte[] dataRead,
+ int dataStartPos, int dataBytesRead)
+ throws IOException
+ {
+ if (contentLength <= 0)
+ {
+ response.setResponseData(new byte[0]);
+ return;
}
- public static boolean init_nss() {
- try {
-
- ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
- client_certdb_pwd, null, null, null);
- cCrypt.setDebug(true);
- cCrypt.setGenerateRequest(false);
- cCrypt.loginDB();
- } catch (Exception e) {
- System.out.println("ERROR: unable to login to : "
- + client_certdb_dir);
- return false;
- }
- return true;
+ byte[] contentBytes = new byte[contentLength];
+ int startPos = 0;
+ if (dataBytesRead > dataStartPos)
+ {
+ // We've already got some data to include in the header, so copy that into
+ // the content array. Make sure the server didn't do something stupid
+ // like return more data than it told us was in the response.
+ int bytesToCopy = Math.min(contentBytes.length,
+ (dataBytesRead - dataStartPos));
+ System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy);
+ startPos = bytesToCopy;
}
- public static void main(String args[]) {
- HTTPClient hc = new HTTPClient();
- HTTPResponse hr = null;
- byte[] responseData = null;
-
- // parse args
- StringHolder x_hostname = new StringHolder();
- StringHolder x_port = new StringHolder();
- StringHolder x_ssl = new StringHolder();
- StringHolder x_client_certdb_dir = new StringHolder();
- StringHolder x_client_certdb_pwd = new StringHolder();
- StringHolder x_client_cert_nickname = new StringHolder();
- StringHolder x_uri = new StringHolder();
- StringHolder x_query = new StringHolder();
- StringHolder x_request_type = new StringHolder();
- StringHolder x_auth_type = new StringHolder();
- StringHolder x_user_id = new StringHolder();
- StringHolder x_user_password = new StringHolder();
- StringHolder x_debug = new StringHolder();
- StringHolder x_decode = new StringHolder();
-
- // parse the args
- ArgParser parser = new ArgParser("HTTPClient");
-
- parser.addOption("-hostname %s #Hostname", x_hostname);
- parser.addOption("-port %s #port number", x_port);
- parser.addOption("-ssl %s #HTTP or HTTPS[true or false]", x_ssl);
- parser.addOption("-client_certdb_dir %s #CertDB dir",
- x_client_certdb_dir);
- parser.addOption("-client_certdb_pwd %s #CertDB password",
- x_client_certdb_pwd);
- parser.addOption("-client_cert_nickname %s #client cert nickname",
- x_client_cert_nickname);
- parser.addOption("-uri %s #URI", x_uri);
- parser.addOption(
- "-query %s #URL encoded query string[note: url encode value part only for CS operations]",
- x_query);
- parser.addOption("-request_type %s #Request Type [ post ]",
- x_request_type);
- parser.addOption("-user_id %s #user id for authorization", x_user_id);
- parser.addOption("-user_password %s #password for authorization",
- x_user_password);
- parser.addOption("-auth_type %s #type of authorization [ BASIC ]",
- x_auth_type);
- parser.addOption("-debug %s #enables display of debugging info",
- x_debug);
- parser.addOption("-decode %s #URL Decode the resulting output",
- x_decode);
-
- // and then match the arguments
- String[] unmatched = null;
- unmatched = parser.matchAllArgs(args, 0, ArgParser.EXIT_ON_UNMATCHED);
-
- if (unmatched != null) {
- System.out.println("ERROR: Argument Mismatch");
- System.exit(-1);
- }
-
- // set variables
- cs_hostname = x_hostname.value;
- cs_port = x_port.value;
- ssl = x_ssl.value;
- client_certdb_dir = x_client_certdb_dir.value;
- client_certdb_pwd = x_client_certdb_pwd.value;
- client_cert_nickname = x_client_cert_nickname.value;
- uri = x_uri.value;
- query = x_query.value;
- request_type = x_request_type.value;
- user_id = x_user_id.value;
- user_password = x_user_password.value;
- auth_type = x_auth_type.value;
- debug = x_debug.value;
-
- String decode = x_decode.value;
-
- // init_nss if needed
- boolean st = init_nss();
- if (!st)
- System.exit(-1);
-
- // set basic auth if needed
- if (auth_type != null && auth_type.equalsIgnoreCase("BASIC")) {
- // BASE64Encoder encoder = new BASE64Encoder();
-
- // String temp = encoder.encodeBuffer((user_id +
- // ":" + user_password).getBytes());
- String temp = OSUtil.BtoA((user_id + ":" + user_password)
- .getBytes());
-
- // note: temp already contains \r and \n.
- // remove \r and \n from the base64 encoded string.
- // causes problems when sending http post requests
- // using PrintStream.println()
-
- temp = temp.replaceAll("\\r", "");
- temp = temp.replaceAll("\\n", "");
-
- basic_auth_header_value = temp;
- }
+ byte[] buffer = new byte[BUFFER_SIZE];
+ while (startPos < contentBytes.length)
+ {
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0)
+ {
+ throw new IOException("Unexpected end of input stream reached when " +
+ "reading data from the server");
+ }
+
+ System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
+ startPos += bytesRead;
+ }
- // route to proper function
- if (ssl != null && ssl.equalsIgnoreCase("true")) {
- if (client_cert_nickname != null
- && !client_cert_nickname.equalsIgnoreCase("null")) {
- // ssl client auth call
+ response.setResponseData(contentBytes);
+ }
+
+ /**
+ * Reads the actual data of the response using chunked encoding, which is a
+ * way for the server to provide the data in several chunks rather than all at
+ * once.
+ *
+ * @param response The response with which the data is associated.
+ * @param inputStream The input stream from which to read the response.
+ * @param dataRead The data that we have already read. This includes
+ * the header data, but may also include some or all of
+ * the content data as well.
+ * @param dataStartPos The position in the provided array at which the
+ * content data starts.
+ * @param dataBytesRead The total number of valid bytes in the provided
+ * array that should be considered part of the
+ * response (the number of header bytes is included in
+ * this count).
+ *
+ * @throws IOException If a problem occurs while reading data from the
+ * server.
+ */
+ private void readContentDataUsingConnectionClose(HTTPResponse response,
+ InputStream inputStream,
+ byte[] dataRead,
+ int dataStartPos,
+ int dataBytesRead)
+ throws IOException
+ {
+ // Create an array list that we will use to hold the chunks of information
+ // read from the server.
+ ArrayList<ByteBuffer> bufferList = new ArrayList<ByteBuffer>();
+
+
+ // Create a variable to hold the total number of bytes in the data.
+ int totalBytes = 0;
+
+
+ // See if we have unread data in the array already provided.
+ int existingBytes = dataBytesRead - dataStartPos;
+ if (existingBytes > 0)
+ {
+ ByteBuffer byteBuffer = ByteBuffer.allocate(existingBytes);
+ byteBuffer.put(dataRead, dataStartPos, existingBytes);
+ bufferList.add(byteBuffer);
+ totalBytes += existingBytes;
+ }
- hr = hc.sslConnectClientAuth(cs_hostname, cs_port,
- client_cert_nickname, uri, query);
- }
- else {
- // ssl client call
- hr = hc.sslConnect(cs_hostname, cs_port, uri, query);
- }
- } else if (ssl != null && ssl.equalsIgnoreCase("false")) {
- // non ssl connect
- hr = hc.nonsslConnect(cs_hostname, cs_port, uri, query);
- } else {
- System.out.println("ERROR: ssl parameter is null");
- System.exit(-1);
+ // Keep reading until we hit the end of the input stream.
+ byte[] buffer = new byte[BUFFER_SIZE];
+ while (true)
+ {
+ try
+ {
+ int bytesRead = inputStream.read(buffer);
+ if (bytesRead < 0)
+ {
+ // We've hit the end of the stream and therefore the end of the
+ // document.
+ break;
}
-
- // collect and print response
-
- responseData = hr.getResponseData();
-
- if (hr.getStatusCode() == 200)
- System.out.println("Response from Host:" + cs_hostname + " OK");
- else {
- System.out.println("ERROR: unable to get response from host:"
- + cs_hostname);
- System.exit(-1);
+ else if (bytesRead > 0)
+ {
+ ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
+ byteBuffer.put(buffer, 0, bytesRead);
+ bufferList.add(byteBuffer);
+ totalBytes += bytesRead;
}
+ }
+ catch (IOException ioe)
+ {
+ // In this case we'll assume that the end of the stream has been
+ // reached. It's possible that there was some other error, but we can't
+ // do anything about it so try to process what we've got so far.
+ System.out.println("ERROR: unable to read until end of stream");
+ System.out.println("ERROR: "+ ioe.getMessage());
+ break;
+ }
+ }
- String responseValue = null;
- if (decode.equalsIgnoreCase("true"))
- responseValue = URLDecoder.decode(hr.getHTML());
- else
- responseValue = hr.getHTML();
-
- System.out.println("###############################");
- System.out.println("RESULT=" + responseValue);
- System.out.println("###############################");
+ // Assemble the contents of all the buffers into a big array and store that
+ // array in the response.
+ int startPos = 0;
+ byte[] contentData = new byte[totalBytes];
+ for (int i=0; i < bufferList.size(); i++)
+ {
+ ByteBuffer byteBuffer = (ByteBuffer) bufferList.get(i);
+ byteBuffer.flip();
+ byteBuffer.get(contentData, startPos, byteBuffer.limit());
+ startPos += byteBuffer.limit();
}
+ response.setResponseData(contentData);
+ }
+
+ // performs ssl connect to given host/port
+ // posts the given query data - format - a byte array
+ // returns HTTPResponse
+
+ public HTTPResponse sslConnect(String hostname, String portnumber,
+ String url, byte[] data)
+ {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+
+ SSLCertificateApprovalCallback approvalCallback =
+ new TestCertApprovalCallback();
+ SSLClientCertificateSelectionCallback certSelectionCallback =
+ new TestClientCertificateSelectionCallback();
+
+ Socket js = new Socket(InetAddress.getByName(hostname), port);
+ SSLSocket socket = new SSLSocket(js, hostname, approvalCallback,
+ certSelectionCallback );
+ setCipherPref(socket);
+ disableSSL2(socket);
+ socket.forceHandshake();
+ System.out.println("Connected.");
+ socket.setUseClientMode(true);
+
+ DataOutputStream dos =
+ new DataOutputStream(socket.getOutputStream());
+ dos.writeBytes("POST /ocsp HTTP/1.0\r\n");
+ dos.writeBytes("Content-length: " + data.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(data);
+ dos.writeBytes("\r\n");
+ dos.flush();
+
+ try
+ {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ dos.close();
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return null;
+ else
+ return hr;
+ }
+
+ // performs non ssl connect to given host/port
+ // posts the given query data
+ // returns HTTPResponse
+ public HTTPResponse nonsslConnect(String hostname, String portnumber,
+ String url, byte[] data)
+ {
+
+ boolean st = true;
+ HTTPResponse hr = null;
+
+ try
+ {
+
+ System.out.println("#############################################");
+ System.out.println("Attempting to connect to: " + hostname + ":" +
+ portnumber);
+
+ Integer x = new Integer(portnumber);
+ int port = x.intValue();
+
+ Socket socket = new Socket(hostname, port);
+
+ System.out.println("Posting Query = " +
+ "http://" + hostname +
+ ":" + portnumber +
+ "/" + url );
+
+ System.out.println("Connected.");
+
+ DataOutputStream dos =
+ new DataOutputStream(socket.getOutputStream());
+ dos.writeBytes("POST " + url + " HTTP/1.0\r\n");
+ dos.writeBytes("Content-length: " + data.length + "\r\n");
+ dos.writeBytes("\r\n");
+ dos.write(data);
+ dos.writeBytes("\r\n");
+ dos.flush();
+
+ try
+ {
+ hr = readResponse(socket.getInputStream());
+ hr.parseContent();
+ }
+ catch (Exception e)
+ {
+ System.out.println("Exception");
+ e.printStackTrace();
+ st = false;
+ }
+
+ socket.close();
+ dos.close();
+
+ }
+
+ catch(Exception e)
+ {
+ System.err.println("Exception: Unable to Send Request:" +e);
+ e.printStackTrace();
+ st = false;
+ }
+
+ if(!st)
+ return null;
+ else
+ return hr;
+ }
+
+ public static boolean init_nss()
+ {
+ try
+ {
+
+ ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
+ client_certdb_pwd,
+ null,
+ null,
+ null);
+ cCrypt.setDebug(true);
+ cCrypt.setGenerateRequest(false);
+ cCrypt.loginDB();
+ }
+ catch(Exception e)
+ {
+ System.out.println("ERROR: unable to login to : " +
+ client_certdb_dir );
+ return false;
+ }
+
+ return true;
+ }
+
+ public static void main(String args[])
+ {
+ HTTPClient hc = new HTTPClient();
+ HTTPResponse hr = null;
+ byte[] responseData = null;
+
+ // parse args
+ StringHolder x_hostname = new StringHolder();
+ StringHolder x_port = new StringHolder();
+ StringHolder x_ssl = new StringHolder();
+ StringHolder x_client_certdb_dir = new StringHolder();
+ StringHolder x_client_certdb_pwd = new StringHolder();
+ StringHolder x_client_cert_nickname = new StringHolder();
+ StringHolder x_uri = new StringHolder();
+ StringHolder x_query = new StringHolder();
+ StringHolder x_request_type = new StringHolder();
+ StringHolder x_auth_type = new StringHolder();
+ StringHolder x_user_id = new StringHolder();
+ StringHolder x_user_password = new StringHolder();
+ StringHolder x_debug = new StringHolder();
+ StringHolder x_decode = new StringHolder();
+
+ // parse the args
+ ArgParser parser = new ArgParser("HTTPClient");
+
+ parser.addOption ("-hostname %s #Hostname",
+ x_hostname);
+ parser.addOption ("-port %s #port number",
+ x_port);
+ parser.addOption ("-ssl %s #HTTP or HTTPS[true or false]",
+ x_ssl);
+ parser.addOption ("-client_certdb_dir %s #CertDB dir",
+ x_client_certdb_dir);
+ parser.addOption ("-client_certdb_pwd %s #CertDB password",
+ x_client_certdb_pwd);
+ parser.addOption ("-client_cert_nickname %s #client cert nickname",
+ x_client_cert_nickname);
+ parser.addOption ("-uri %s #URI",
+ x_uri);
+ parser.addOption ("-query %s #URL encoded query string[note: url encode value part only for CS operations]",
+ x_query);
+ parser.addOption ("-request_type %s #Request Type [ post ]",
+ x_request_type);
+ parser.addOption ("-user_id %s #user id for authorization",
+ x_user_id);
+ parser.addOption ("-user_password %s #password for authorization",
+ x_user_password);
+ parser.addOption ("-auth_type %s #type of authorization [ BASIC ]",
+ x_auth_type);
+ parser.addOption ("-debug %s #enables display of debugging info",
+ x_debug);
+ parser.addOption ("-decode %s #URL Decode the resulting output" ,
+ x_decode);
+
+ // and then match the arguments
+ String [] unmatched = null;
+ unmatched = parser.matchAllArgs (args,0,ArgParser.EXIT_ON_UNMATCHED);
+
+ if(unmatched!=null)
+ {
+ System.out.println("ERROR: Argument Mismatch");
+ System.exit(-1);
+ }
+
+ // set variables
+ cs_hostname = x_hostname.value;
+ cs_port = x_port.value;
+ ssl = x_ssl.value;
+ client_certdb_dir = x_client_certdb_dir.value;
+ client_certdb_pwd = x_client_certdb_pwd.value;
+ client_cert_nickname = x_client_cert_nickname.value;
+ uri = x_uri.value;
+ query = x_query.value;
+ request_type = x_request_type.value;
+ user_id = x_user_id.value;
+ user_password = x_user_password.value;
+ auth_type = x_auth_type.value;
+ debug = x_debug.value;
+
+ String decode = x_decode.value;
+
+ // init_nss if needed
+ boolean st = init_nss();
+ if(!st)
+ System.exit(-1);
+
+ // set basic auth if needed
+ if(auth_type != null && auth_type.equalsIgnoreCase("BASIC"))
+ {
+ // BASE64Encoder encoder = new BASE64Encoder();
+
+ // String temp = encoder.encodeBuffer((user_id +
+ // ":" + user_password).getBytes());
+ String temp = OSUtil.BtoA((user_id +
+ ":" + user_password).getBytes());
+
+ // note: temp already contains \r and \n.
+ // remove \r and \n from the base64 encoded string.
+ // causes problems when sending http post requests
+ // using PrintStream.println()
+
+ temp = temp.replaceAll("\\r" , "");
+ temp = temp.replaceAll("\\n" , "");
+
+ basic_auth_header_value = temp;
+ }
+
+ // route to proper function
+
+ if(ssl != null && ssl.equalsIgnoreCase("true"))
+ {
+ if(client_cert_nickname != null &&
+ !client_cert_nickname.equalsIgnoreCase("null"))
+ {
+ // ssl client auth call
+
+ hr = hc.sslConnectClientAuth(cs_hostname,cs_port,
+ client_cert_nickname,
+ uri,query);
+ }
+
+ else
+ {
+ // ssl client call
+ hr = hc.sslConnect(cs_hostname,cs_port,uri,query);
+ }
+ }
+ else if(ssl!=null && ssl.equalsIgnoreCase("false"))
+ {
+ // non ssl connect
+ hr = hc.nonsslConnect(cs_hostname,cs_port,uri,query);
+ }
+ else
+ {
+ System.out.println("ERROR: ssl parameter is null");
+ System.exit(-1);
+ }
+
+
+ // collect and print response
+
+ responseData = hr.getResponseData();
+
+ if(hr.getStatusCode() == 200)
+ System.out.println("Response from Host:" + cs_hostname + " OK");
+ else
+ {
+ System.out.println("ERROR: unable to get response from host:" +
+ cs_hostname);
+ System.exit(-1);
+ }
+
+ String responseValue = null;
+ if(decode.equalsIgnoreCase("true"))
+ responseValue = URLDecoder.decode(hr.getHTML());
+ else
+ responseValue = hr.getHTML();
+
+
+ System.out.println("###############################");
+ System.out.println("RESULT=" + responseValue);
+ System.out.println("###############################");
+
+ }
};
diff --git a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
index 67a3cf74..08358f35 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
@@ -1,5 +1,4 @@
package com.netscape.pkisilent.http;
-
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
@@ -18,299 +17,369 @@ package com.netscape.pkisilent.http;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
+
import java.util.ArrayList;
import java.util.StringTokenizer;
import com.netscape.pkisilent.common.Utilities;
-public class HTTPResponse {
- // The set of cookie values included in this response.
- ArrayList<String> cookieValueList;
-
- // The names of the headers included in this response.
- ArrayList<String> headerNameList;
-
- // The values of the headers included in this response.
- ArrayList<String> headerValueList;
-
- // The actual data associated with this response.
- byte[] responseData;
-
- // The HTML document included in the response, if appropriate.
- HTMLDocument htmlDocument;
-
- // The number of bytes contained in the content of the response.
- int contentLength;
-
- // The HTTP status code for the response.
- int statusCode;
-
- // The MIME type of the response.
- String contentType;
-
- // The protocol version string for this response.
- String protolVersion;
-
- // The response message for this response.
- String responseMessage;
-
- // Parsed Content Name/Value pair info
- ArrayList<String> contentName;
- ArrayList<String> contentValue;
-
- /**
- * Creates a new HTTP response with the provided status code.
- *
- * @param statusCode The HTTP status code for this response.
- * @param protocolVersion The protocol and version for this response.
- * @param responseMessage The message associated with this response.
- */
- public HTTPResponse(int statusCode, String protocolVersion,
- String responseMessage) {
- this.statusCode = statusCode;
- this.protolVersion = protocolVersion;
- this.responseMessage = responseMessage;
-
- htmlDocument = null;
- contentType = null;
- contentLength = -1;
- responseData = new byte[0];
- cookieValueList = new ArrayList<String>();
- headerNameList = new ArrayList<String>();
- headerValueList = new ArrayList<String>();
- contentName = new ArrayList<String>();
- contentValue = new ArrayList<String>();
- }
-
- /**
- * Retrieves the status code for this HTTP response.
- *
- * @return The status code for this HTTP response.
- */
- public int getStatusCode() {
- return statusCode;
- }
-
- /**
- * Retrieves the protocol version for this HTTP response.
- *
- * @return The protocol version for this HTTP response.
- */
- public String getProtocolVersion() {
- return protolVersion;
- }
-
- /**
- * Retrieves the response message for this HTTP response.
- *
- * @return The response message for this HTTP response.
- */
- public String getResponseMessage() {
- return responseMessage;
- }
- /**
- * Retrieves the value of the header with the specified name. If the
- * specified header has more than one value, then only the first will be
- * retrieved.
- *
- * @return The value of the header with the specified name, or
- * <CODE>null</CODE> if no such header is available.
- */
- public String getHeader(String headerName) {
- String lowerName = headerName.toLowerCase();
-
- for (int i = 0; i < headerNameList.size(); i++) {
- if (lowerName.equals(headerNameList.get(i))) {
- return headerValueList.get(i);
- }
- }
-
- return null;
- }
+public class HTTPResponse
+{
+ // The set of cookie values included in this response.
+ ArrayList<String> cookieValueList;
- /**
- * Retrieves the set of values for the specified header.
- *
- * @return The set of values for the specified header.
- */
- public String[] getHeaderValues(String headerName) {
- ArrayList<String> valueList = new ArrayList<String>();
- String lowerName = headerName.toLowerCase();
-
- for (int i = 0; i < headerNameList.size(); i++) {
- if (lowerName.equals(headerNameList.get(i))) {
- valueList.add(headerValueList.get(i));
- }
- }
-
- String[] values = new String[valueList.size()];
- valueList.toArray(values);
- return values;
- }
+ // The names of the headers included in this response.
+ ArrayList<String> headerNameList;
- /**
- * Adds a header with the given name and value to this response.
- *
- * @param headerName The name of the header to add to this response.
- * @param headerValue The value of the header to add to this response.
- */
- public void addHeader(String headerName, String headerValue) {
- String lowerName = headerName.toLowerCase();
- headerNameList.add(lowerName);
- headerValueList.add(headerValue);
-
- if (lowerName.equals("content-length")) {
- try {
- contentLength = Integer.parseInt(headerValue);
- } catch (NumberFormatException nfe) {
- }
- } else if (lowerName.equals("content-type")) {
- contentType = headerValue;
- } else if (lowerName.equals("set-cookie")) {
- cookieValueList.add(headerValue);
- }
- }
-
- /**
- * Retrieves a two-dimensional array containing the header data for this
- * response, with each element being an array containing a name/value pair.
- *
- * @return A two-dimensional array containing the header data for this
- * response.
- */
- public String[][] getHeaderElements() {
- String[][] headerElements = new String[headerNameList.size()][2];
- for (int i = 0; i < headerNameList.size(); i++) {
- headerElements[i][0] = headerNameList.get(i);
- headerElements[i][1] = headerValueList.get(i);
- }
-
- return headerElements;
- }
+ // The values of the headers included in this response.
+ ArrayList<String> headerValueList;
- /**
- * Retrieves the raw data included in this HTTP response. If the response
- * did not include any data, an empty array will be returned.
- *
- * @return The raw data included in this HTTP response.
- */
- public byte[] getResponseData() {
- return responseData;
- }
+ // The actual data associated with this response.
+ byte[] responseData;
- public String getHTML() {
- String htmlString = new String(responseData);
- return htmlString;
- }
+ // The HTML document included in the response, if appropriate.
+ HTMLDocument htmlDocument;
- public String getHTMLwithoutTags() {
- String htmlString = new String(responseData);
- HTMLDocument htmldocument = new HTMLDocument(htmlString);
- return htmldocument.getTextData();
+ // The number of bytes contained in the content of the response.
+ int contentLength;
+
+ // The HTTP status code for the response.
+ int statusCode;
+
+ // The MIME type of the response.
+ String contentType;
+
+ // The protocol version string for this response.
+ String protolVersion;
+
+ // The response message for this response.
+ String responseMessage;
+
+ // Parsed Content Name/Value pair info
+ ArrayList<String> contentName;
+ ArrayList<String> contentValue;
+
+
+
+ /**
+ * Creates a new HTTP response with the provided status code.
+ *
+ * @param statusCode The HTTP status code for this response.
+ * @param protocolVersion The protocol and version for this response.
+ * @param responseMessage The message associated with this response.
+ */
+ public HTTPResponse(int statusCode, String protocolVersion,
+ String responseMessage)
+ {
+ this.statusCode = statusCode;
+ this.protolVersion = protocolVersion;
+ this.responseMessage = responseMessage;
+
+ htmlDocument = null;
+ contentType = null;
+ contentLength = -1;
+ responseData = new byte[0];
+ cookieValueList = new ArrayList<String>();
+ headerNameList = new ArrayList<String>();
+ headerValueList = new ArrayList<String>();
+ contentName = new ArrayList<String>();
+ contentValue = new ArrayList<String>();
+ }
+
+
+
+ /**
+ * Retrieves the status code for this HTTP response.
+ *
+ * @return The status code for this HTTP response.
+ */
+ public int getStatusCode()
+ {
+ return statusCode;
+ }
+
+
+
+ /**
+ * Retrieves the protocol version for this HTTP response.
+ *
+ * @return The protocol version for this HTTP response.
+ */
+ public String getProtocolVersion()
+ {
+ return protolVersion;
+ }
+
+
+
+ /**
+ * Retrieves the response message for this HTTP response.
+ *
+ * @return The response message for this HTTP response.
+ */
+ public String getResponseMessage()
+ {
+ return responseMessage;
+ }
+
+
+
+ /**
+ * Retrieves the value of the header with the specified name. If the
+ * specified header has more than one value, then only the first will be
+ * retrieved.
+ *
+ * @return The value of the header with the specified name, or
+ * <CODE>null</CODE> if no such header is available.
+ */
+ public String getHeader(String headerName)
+ {
+ String lowerName = headerName.toLowerCase();
+
+ for (int i=0; i < headerNameList.size(); i++)
+ {
+ if (lowerName.equals(headerNameList.get(i)))
+ {
+ return headerValueList.get(i);
+ }
}
- public void parseContent() {
- // parse the responseData byte[] buffer and split content into name
- // value pair
- String htmlString = new String(responseData);
- StringTokenizer st = new StringTokenizer(htmlString, "\n");
- Utilities ut = new Utilities();
+ return null;
+ }
- while (st.hasMoreTokens()) {
- String line = st.nextToken();
- // format for line assumed to be name="value"; format
- int eqPos = line.indexOf('=');
- if (eqPos != -1) {
- String name = line.substring(0, eqPos);
- String tempval = line.substring(eqPos + 1).trim();
- String value = ut.cleanupQuotes(ut.removechar(tempval));
- // add to array
- this.contentName.add(name.trim());
- this.contentValue.add(value);
- }
-
- }
+ /**
+ * Retrieves the set of values for the specified header.
+ *
+ * @return The set of values for the specified header.
+ */
+ public String[] getHeaderValues(String headerName)
+ {
+ ArrayList<String> valueList = new ArrayList<String>();
+ String lowerName = headerName.toLowerCase();
+ for (int i=0; i < headerNameList.size(); i++)
+ {
+ if (lowerName.equals(headerNameList.get(i)))
+ {
+ valueList.add(headerValueList.get(i));
+ }
}
- public String getContentValue(String headerName) {
- for (int i = 0; i < contentName.size(); i++) {
- if (headerName.equals(contentName.get(i))) {
- return contentValue.get(i);
- }
- }
-
- return null;
+ String[] values = new String[valueList.size()];
+ valueList.toArray(values);
+ return values;
+ }
+
+
+
+ /**
+ * Adds a header with the given name and value to this response.
+ *
+ * @param headerName The name of the header to add to this response.
+ * @param headerValue The value of the header to add to this response.
+ */
+ public void addHeader(String headerName, String headerValue)
+ {
+ String lowerName = headerName.toLowerCase();
+ headerNameList.add(lowerName);
+ headerValueList.add(headerValue);
+
+ if (lowerName.equals("content-length"))
+ {
+ try
+ {
+ contentLength = Integer.parseInt(headerValue);
+ } catch (NumberFormatException nfe) {}
}
-
- public ArrayList<String> getContentNames() {
- return contentName;
- }
-
- public ArrayList<String> getContentValues() {
- return contentValue;
+ else if (lowerName.equals("content-type"))
+ {
+ contentType = headerValue;
}
-
- /**
- * Sets the actual data associated with this response.
- *
- * @param responseData The actual data associated with this response.
- */
- public void setResponseData(byte[] responseData) {
- if (responseData == null) {
- this.responseData = new byte[0];
- } else {
- this.responseData = responseData;
- }
+ else if (lowerName.equals("set-cookie"))
+ {
+ cookieValueList.add(headerValue);
}
-
- /**
- * Retrieves the content length associated with this response.
- *
- * @return The content length associated with this response, or -1 if no
- * content length is available.
- */
- public int getContentLength() {
- return contentLength;
+ }
+
+
+
+ /**
+ * Retrieves a two-dimensional array containing the header data for this
+ * response, with each element being an array containing a name/value pair.
+ *
+ * @return A two-dimensional array containing the header data for this
+ * response.
+ */
+ public String[][] getHeaderElements()
+ {
+ String[][] headerElements = new String[headerNameList.size()][2];
+ for (int i=0; i < headerNameList.size(); i++)
+ {
+ headerElements[i][0] = headerNameList.get(i);
+ headerElements[i][1] = headerValueList.get(i);
}
- /**
- * Retrieves the content type associated with this response.
- *
- * @return The content type associated with this response, or
- * <CODE>null</CODE> if no content type is available.
- */
- public String getContentType() {
- return contentType;
+ return headerElements;
+ }
+
+
+
+ /**
+ * Retrieves the raw data included in this HTTP response. If the response did
+ * not include any data, an empty array will be returned.
+ *
+ * @return The raw data included in this HTTP response.
+ */
+ public byte[] getResponseData()
+ {
+ return responseData;
+ }
+
+
+ public String getHTML()
+ {
+ String htmlString = new String(responseData);
+ return htmlString;
+ }
+
+ public String getHTMLwithoutTags()
+ {
+ String htmlString = new String(responseData);
+ HTMLDocument htmldocument = new HTMLDocument(htmlString);
+ return htmldocument.getTextData();
+ }
+ public void parseContent()
+ {
+ // parse the responseData byte[] buffer and split content into name
+ // value pair
+ String htmlString = new String(responseData);
+ StringTokenizer st = new StringTokenizer(htmlString, "\n");
+ Utilities ut = new Utilities();
+
+ while(st.hasMoreTokens())
+ {
+ String line = st.nextToken();
+ // format for line assumed to be name="value"; format
+
+ int eqPos = line.indexOf('=') ;
+ if(eqPos != -1)
+ {
+ String name = line.substring(0,eqPos);
+ String tempval = line.substring(eqPos+1).trim();
+ String value = ut.cleanupQuotes(ut.removechar(tempval));
+
+ // add to array
+ this.contentName.add(name.trim());
+ this.contentValue.add(value);
+ }
+
+ }
+
+ }
+
+
+
+ public String getContentValue(String headerName)
+ {
+ for (int i=0; i < contentName.size(); i++)
+ {
+ if (headerName.equals(contentName.get(i)))
+ {
+ return contentValue.get(i);
+ }
+ }
+
+ return null;
+ }
+
+ public ArrayList<String> getContentNames()
+ {
+ return contentName;
+ }
+
+ public ArrayList<String> getContentValues()
+ {
+ return contentValue;
+ }
+
+ /**
+ * Sets the actual data associated with this response.
+ *
+ * @param responseData The actual data associated with this response.
+ */
+ public void setResponseData(byte[] responseData)
+ {
+ if (responseData == null)
+ {
+ this.responseData = new byte[0];
}
-
- /**
- * Retrieves an array containing the values of the cookies that should be
- * set based on the information in this response.
- *
- * @return An array containing the values of the cookies that should be set
- * based on the information in this response.
- */
- public String[] getCookieValues() {
- String[] cookieValues = new String[cookieValueList.size()];
- cookieValueList.toArray(cookieValues);
- return cookieValues;
+ else
+ {
+ this.responseData = responseData;
}
+ }
+
+
+
+ /**
+ * Retrieves the content length associated with this response.
+ *
+ * @return The content length associated with this response, or -1 if no
+ * content length is available.
+ */
+ public int getContentLength()
+ {
+ return contentLength;
+ }
+
+
+
+ /**
+ * Retrieves the content type associated with this response.
+ *
+ * @return The content type associated with this response, or
+ * <CODE>null</CODE> if no content type is available.
+ */
+ public String getContentType()
+ {
+ return contentType;
+ }
+
+
+
+ /**
+ * Retrieves an array containing the values of the cookies that should be set
+ * based on the information in this response.
+ *
+ * @return An array containing the values of the cookies that should be set
+ * based on the information in this response.
+ */
+ public String[] getCookieValues()
+ {
+ String[] cookieValues = new String[cookieValueList.size()];
+ cookieValueList.toArray(cookieValues);
+ return cookieValues;
+ }
+
+ public String getCookieValue(String headerName)
+ {
+ for (int i=0; i < cookieValueList.size(); i++)
+ {
+ System.out.println("cookie list: " + cookieValueList.get(i));
+
+ String temp = cookieValueList.get(i);
+ if (temp.startsWith(headerName))
+ {
+ return cookieValueList.get(i);
+ }
+ }
+
+ return null;
+ }
- public String getCookieValue(String headerName) {
- for (int i = 0; i < cookieValueList.size(); i++) {
- System.out.println("cookie list: " + cookieValueList.get(i));
-
- String temp = cookieValueList.get(i);
- if (temp.startsWith(headerName)) {
- return cookieValueList.get(i);
- }
- }
-
- return null;
- }
}
+