summaryrefslogtreecommitdiffstats
path: root/pki/base/silent/src/com/netscape/pkisilent
diff options
context:
space:
mode:
Diffstat (limited to 'pki/base/silent/src/com/netscape/pkisilent')
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java622
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java623
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java524
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java1755
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java596
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java516
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java2240
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java11
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/PKISilent.java97
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java54
-rwxr-xr-xpki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java3963
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java3021
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java54
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java56
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java55
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java56
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java55
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java55
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java54
-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.java55
-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.java98
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java34
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java13
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java49
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java77
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java282
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java10
-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.java106
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java33
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java61
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java19
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java17
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Request.java151
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java48
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java85
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java62
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java18
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java78
-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.java1182
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java2349
-rw-r--r--pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java603
46 files changed, 9964 insertions, 11200 deletions
diff --git a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
index 337bf927..a7b11408 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureCA.java
@@ -1,4 +1,5 @@
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
@@ -17,7 +18,6 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -41,10 +41,8 @@ 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";
@@ -57,7 +55,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";
@@ -171,7 +169,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;
@@ -185,7 +183,6 @@ public class ConfigureCA {
//for correct selection of CA to be cloned
public static String urls;
-
public ConfigureCA() {// do nothing :)
}
@@ -206,34 +203,33 @@ public class ConfigureCA {
public boolean checkStatus(HTTPResponse hr, String name,
String expected, String location) {
- return checkStatus(hr,name, new String[] {expected}, location);
- }
+ return checkStatus(hr, name, new String[] { expected }, location);
+ }
- public boolean checkStatus(HTTPResponse hr, String name,
+ 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 +
+ 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 +
+ 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());
@@ -250,8 +246,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;
}
@@ -272,27 +268,27 @@ 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") + "";
+ + URLEncoder.encode("Internal Key Storage Token") + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
+ 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) + "";
+ + 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()")) {
+ 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) + "";
+ + URLEncoder.encode(token_name) + "";
hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- if (! checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "TokenChoicePanel()")) {
return false;
}
}
@@ -310,19 +306,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;
}
@@ -338,7 +334,7 @@ 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());
@@ -353,42 +349,42 @@ public class ConfigureCA {
HTTPResponse hr = null;
String subca_url = "https://" + cs_hostname + ":" + cs_port +
- "/ca/admin/console/config/wizard" + "?p=5&subsystem=CA" ;
+ "/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) ;
+ "&url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ 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);
+ "&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());
e.printStackTrace();
@@ -397,33 +393,33 @@ public class ConfigureCA {
}
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;
}
}
@@ -440,12 +436,12 @@ 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;
@@ -455,21 +451,20 @@ public class ConfigureCA {
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;
}
@@ -488,19 +483,19 @@ public class ConfigureCA {
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": "");
+ + 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;
}
@@ -521,48 +516,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;
}
@@ -574,7 +569,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;
@@ -589,13 +584,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);
+ "default: ca_subsystem_cert_name=" + ca_subsystem_cert_name);
System.out.println(
- "default: ca_audit_signing_cert_name=" + ca_audit_signing_cert_name);
+ "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) {
@@ -620,27 +615,27 @@ public class ConfigureCA {
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"
- + "";
+ + 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"
- + "";
- }
+ + 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");
@@ -652,46 +647,44 @@ 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 {
+ try {
FileOutputStream fos = new FileOutputStream(ext_csr_file);
- PrintStream p = new PrintStream( fos );
+ 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);
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) {
+ } 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;
@@ -701,32 +694,32 @@ 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
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);
+ "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);
@@ -759,17 +752,17 @@ public class ConfigureCA {
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=" + "";
+ + 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;
}
@@ -795,18 +788,18 @@ public class ConfigureCA {
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=" + "";
+ + 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;
}
@@ -824,23 +817,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);
}
}
}
@@ -849,10 +842,10 @@ public class ConfigureCA {
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);
+ "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);
+ "ca_audit_signing_cert_name=" + ca_audit_signing_cert_subject_name);
// print out requests
System.out.println("ca_cert_req=" + ca_cert_req);
@@ -884,15 +877,15 @@ 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()")) {
+ if (!checkStatus(hr, "updateStatus", SUCCESS, "BackupPanel()")) {
return false;
}
- query_string = "";
+ query_string = "";
hr = hc.sslConnect(cs_hostname, cs_port, pkcs12_uri, query_string);
@@ -905,13 +898,13 @@ 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()));
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
@@ -928,7 +921,7 @@ public class ConfigureCA {
SEQUENCE asSeq = authSafes.getSequence();
System.out.println(
- "AuthSafes has " + asSeq.size() + " SafeContents");
+ "AuthSafes has " + asSeq.size() + " SafeContents");
fis.close();
} catch (Exception e) {
@@ -950,12 +943,12 @@ 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());
e.printStackTrace();
@@ -968,12 +961,12 @@ 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());
e.printStackTrace();
@@ -990,7 +983,7 @@ public class ConfigureCA {
String admin_cert_request = null;
ComCrypto cCrypt = new ComCrypto(client_certdb_dir, client_certdb_pwd,
- agent_cert_subject, agent_key_size, agent_key_type);
+ agent_cert_subject, agent_key_size, agent_key_type);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1008,25 +1001,25 @@ public class ConfigureCA {
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;
@@ -1045,10 +1038,10 @@ 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
@@ -1066,7 +1059,7 @@ 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);
+ null, null, null);
cCrypt.setDebug(true);
cCrypt.setGenerateRequest(true);
@@ -1078,7 +1071,7 @@ public class ConfigureCA {
st = cCrypt.importCert(start + cert_to_import + end, agent_name);
if (!st) {
System.out.println(
- "ERROR: AdminCertImportPanel() during cert import");
+ "ERROR: AdminCertImportPanel() during cert import");
return false;
}
@@ -1099,18 +1092,18 @@ public class ConfigureCA {
ParseXML px = new ParseXML();
String query_string = "p=17" + "&op=next" + "&xml=true" + "&caHost="
- + URLEncoder.encode("/") + "&caPort=" + URLEncoder.encode("/")
- + "";
+ + 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");
@@ -1118,7 +1111,7 @@ 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());
@@ -1173,14 +1166,13 @@ public class ConfigureCA {
// 4. display cert chain panel and security domain login
if (clone) {
boolean disp_st = DisplayCertChainPanel();
- if(!disp_st) {
+ if (!disp_st) {
System.out.println("ERROR: ConfigureCA: DisplayCertChainPanel() failure");
return false;
}
boolean sd_st = SecurityDomainLoginPanel();
- if(! sd_st)
- {
+ if (!sd_st) {
System.out.println("ERROR: ConfigureSubCA: SecurityDomainLoginPanel() failure");
return false;
}
@@ -1205,7 +1197,7 @@ public class ConfigureCA {
}
// 7. hierarchy panel
- if (! clone) {
+ if (!clone) {
boolean disp_h = HierarchyPanel();
if (!disp_h) {
@@ -1251,12 +1243,11 @@ public class ConfigureCA {
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;
}
}
@@ -1283,7 +1274,6 @@ public class ConfigureCA {
return false;
}
-
// 15. Import CA Cert panel
boolean disp_import_cacert = ImportCACertPanel();
@@ -1291,13 +1281,12 @@ public class ConfigureCA {
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();
@@ -1379,7 +1368,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();
@@ -1421,9 +1410,9 @@ 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
StringHolder x_clone = new StringHolder();
@@ -1439,105 +1428,104 @@ 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_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_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_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);
+ 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);
+ 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("-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_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);
+ 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);
+ 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);
-
+ x_subsystem_name);
+
parser.addOption("-external %s #Subordinate to external CA [true,false] (optional, default false)",
- x_external_ca);
+ x_external_ca);
parser.addOption("-ext_ca_cert_file %s #File with CA cert from external CA (optional)",
- x_ext_ca_cert_file);
+ 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)",
@@ -1548,15 +1536,14 @@ public class ConfigureCA {
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;
@@ -1618,11 +1605,11 @@ public class ConfigureCA {
} else {
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);
-
+
token_name = x_token_name.value;
token_pwd = x_token_pwd.value;
save_p12 = x_save_p12.value;
@@ -1638,9 +1625,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;
@@ -1663,18 +1650,15 @@ 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 c79ec4ed..0b771d8f 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureDRM.java
@@ -1,4 +1,5 @@
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
@@ -17,7 +18,6 @@ package com.netscape.pkisilent;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
@@ -39,8 +39,7 @@ 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";
@@ -52,7 +51,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";
@@ -167,7 +166,6 @@ public class ConfigureDRM
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
@@ -178,36 +176,30 @@ public class ConfigureDRM
//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
@@ -215,14 +207,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());
@@ -232,8 +224,7 @@ public class ConfigureDRM
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -244,9 +235,9 @@ public class ConfigureDRM
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token");
- 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,22 +246,22 @@ public class ConfigureDRM
} else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
- URLEncoder.encode(token_pwd);
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "&__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=" +
+ "&choice=" +
URLEncoder.encode(token_name);
- 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());
@@ -281,24 +272,22 @@ 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 domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&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());
@@ -309,23 +298,21 @@ 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;
@@ -334,17 +321,17 @@ public class ConfigureDRM
String kra_url = "https://" + cs_hostname + ":" + cs_port +
"/kra/admin/console/config/wizard" +
- "?p=5&subsystem=KRA" ;
+ "?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) ;
+ "&url=" + URLEncoder.encode(kra_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -360,9 +347,9 @@ public class ConfigureDRM
String query_string_2 = "p=5" +
"&subsystem=KRA" +
"&session_id=" + kra_session_id +
- "&xml=true" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
if (clone) {
@@ -372,7 +359,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);
@@ -385,9 +372,8 @@ public class ConfigureDRM
return false;
}
}
-
- public boolean SubsystemPanel()
- {
+
+ public boolean SubsystemPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -395,16 +381,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);
@@ -420,8 +406,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);
@@ -437,27 +423,25 @@ public class ConfigureDRM
}
}
- 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) +
+ "&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": "");
+ "&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);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -467,8 +451,7 @@ public class ConfigureDRM
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -479,55 +462,55 @@ public class ConfigureDRM
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;
+ "&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";
- }
+ "&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) {
@@ -541,23 +524,22 @@ 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_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);
+ drm_audit_signing_cert_name);
- System.out.println("default: server_cert_name=" +
- server_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;
@@ -567,69 +549,68 @@ 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);
+ "&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);
+ "&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;
@@ -639,68 +620,63 @@ public class ConfigureDRM
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(drm_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&transport=" +
+ "&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=" +
+ "&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);
+ 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" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- 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 SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- 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
try {
@@ -709,17 +685,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()));
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();
@@ -727,17 +703,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());
@@ -752,8 +728,7 @@ public class ConfigureDRM
return true;
}
- public boolean AdminCertReqPanel()
- {
+ public boolean AdminCertReqPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -775,7 +750,7 @@ public class ConfigureDRM
if (crmf_request == null) {
System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ return false;
}
admin_cert_request = crmf_request;
@@ -787,31 +762,30 @@ public class ConfigureDRM
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
"&clone=new" +
"&import=true" +
"&securitydomain=" +
- URLEncoder.encode(domain_name);
+ URLEncoder.encode(domain_name);
- 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();
-
- 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;
@@ -820,13 +794,13 @@ public class ConfigureDRM
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true";
- hr = hc.sslConnect(sd_hostname,sd_admin_port,admin_uri,query_string);
-
+ 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 =
+ OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
ComCrypto cCrypt = new ComCrypto(client_certdb_dir,
@@ -838,10 +812,10 @@ public class ConfigureDRM
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");
return false;
@@ -851,8 +825,7 @@ public class ConfigureDRM
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -862,18 +835,17 @@ public class ConfigureDRM
"&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,
@@ -1034,8 +1006,7 @@ public class ConfigureDRM
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureDRM ca = new ConfigureDRM();
// set variables
@@ -1136,63 +1107,63 @@ 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);
@@ -1226,43 +1197,43 @@ public class ConfigureDRM
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("-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("-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_pwd %s #PKCS12 password",
+ x_backup_pwd);
- parser.addOption("-backup_fname %s #Backup File for p12, (optional, default /root/tmp-kra.p12)",
+ 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",
+ 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_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(
- "-drm_audit_signing_cert_subject_name %s #DRM audit signing cert subject name",
+ "-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);
@@ -1271,10 +1242,10 @@ public class ConfigureDRM
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);
}
@@ -1354,15 +1325,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"))) {
@@ -1375,12 +1346,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 f237b0c7..c69a3f7b 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureOCSP.java
@@ -1,4 +1,5 @@
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
@@ -38,8 +39,7 @@ 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";
@@ -155,35 +155,30 @@ public class ConfigureOCSP
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
@@ -191,14 +186,14 @@ 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,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -211,8 +206,7 @@ public class ConfigureOCSP
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -223,10 +217,10 @@ public class ConfigureOCSP
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- 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);
@@ -236,23 +230,23 @@ public class ConfigureOCSP
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- 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();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- 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);
@@ -262,24 +256,22 @@ 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 domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&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());
@@ -290,16 +282,15 @@ 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);
@@ -309,27 +300,25 @@ 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" ;
+ "?p=5&subsystem=OCSP";
- String query_string = "url=" + URLEncoder.encode(ocsp_url);
+ String query_string = "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_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(ocsp_url) ;
+ "&url=" + URLEncoder.encode(ocsp_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -337,17 +326,17 @@ public class ConfigureOCSP
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" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
// parse xml
@@ -358,20 +347,19 @@ 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" +
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
"&subsystemName=" +
- URLEncoder.encode(subsystem_name) +
- "&choice=newsubsystem" ;
+ 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);
@@ -380,27 +368,25 @@ 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) +
+ "&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": "");
+ (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);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -410,8 +396,7 @@ public class ConfigureOCSP
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -429,31 +414,31 @@ public class ConfigureOCSP
"&sslserver_custom_curvename=" + sslserver_key_curvename +
"&audit_signing_custom_curvename=" + audit_signing_key_curvename +
"&custom_curvename=" + key_curvename +
- "&signing_keytype=" + signing_key_type +
+ "&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"+
+ "&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);
+ 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) {
@@ -465,7 +450,7 @@ 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: server_cert_name=" + server_cert_name);
@@ -474,8 +459,7 @@ public class ConfigureOCSP
return true;
}
- public boolean CertSubjectPanel()
- {
+ public boolean CertSubjectPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -484,57 +468,56 @@ 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=" +
+ "&subsystem=" +
URLEncoder.encode(ocsp_subsystem_cert_subject_name) +
- "&signing=" +
- URLEncoder.encode(ocsp_sign_cert_subject_name) +
- "&sslserver=" +
- URLEncoder.encode(ocsp_server_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) +
- "";
+ "&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;
@@ -544,69 +527,64 @@ public class ConfigureOCSP
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&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=" +
+ "&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);
+ 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" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- 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 SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- 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
@@ -616,17 +594,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()));
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();
@@ -634,14 +612,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;
}
@@ -649,15 +627,13 @@ 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,
@@ -687,9 +663,9 @@ public class ConfigureOCSP
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
@@ -697,22 +673,21 @@ public class ConfigureOCSP
"&import=true" +
"&securitydomain=" +
URLEncoder.encode(domain_name) +
- "";
+ "";
- 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();
-
- 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;
@@ -720,14 +695,14 @@ public class ConfigureOCSP
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
- 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 =
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -740,10 +715,10 @@ public class ConfigureOCSP
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");
return false;
@@ -753,8 +728,7 @@ public class ConfigureOCSP
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -763,21 +737,19 @@ public class ConfigureOCSP
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,
@@ -802,7 +774,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;
}
@@ -837,7 +809,7 @@ public class ConfigureOCSP
System.out.println("ERROR: ConfigureOCSP: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
@@ -923,8 +895,7 @@ public class ConfigureOCSP
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureOCSP ca = new ConfigureOCSP();
// set variables
@@ -1013,63 +984,63 @@ 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);
@@ -1098,47 +1069,47 @@ public class ConfigureOCSP
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("-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("-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_pwd %s #PKCS12 password",
+ x_backup_pwd);
- parser.addOption (
- "-ocsp_sign_cert_subject_name %s #OCSP cert subject name",
+ 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",
+ 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(
+ "-subsystem_name %s #OCSP subsystem name",
+ x_subsystem_name);
parser.addOption(
- "-ocsp_audit_signing_cert_subject_name %s #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);
}
@@ -1214,26 +1185,25 @@ 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 fc28e8b4..a9345cc5 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureRA.java
@@ -1,4 +1,5 @@
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
@@ -29,927 +30,875 @@ 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 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";
- 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");
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
- 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
+ bais = new ByteArrayInputStream(hr.getHTML().getBytes());
+ px.parse(bais);
+ px.prettyprintxml();
- // parse xml here
+ return true;
- bais = new ByteArrayInputStream(
- hr.getHTML().getBytes());
- px.parse(bais);
- px.prettyprintxml();
+ }
- st = true;
- return st;
- }
+ public boolean DisplayChainPanel() {
+ boolean st = false;
+ HTTPResponse hr = null;
+ ByteArrayInputStream bais = null;
+ ParseXML px = new ParseXML();
+ String query_string = null;
- 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;
+ 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();
+ }
+ 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 ra_url = "https://" + cs_hostname + ":" + cs_port +
+ "/ra/admin/console/config/wizard" +
+ "?p=3&subsystem=RA";
- String query_string = "url=" + URLEncoder.encode(ra_url) + "";
+ String query_string = "url=" + URLEncoder.encode(ra_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(ra_url) +
- "" ;
+ 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);
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
+ query_string_1);
- // get session id from security domain
- sleep_time();
+ // get session id from security domain
+ sleep_time();
- ra_session_id = hr.getContentValue("header.session_id");
- String ra_url_1 = hr.getContentValue("header.url");
+ ra_session_id = hr.getContentValue("header.session_id");
+ String ra_url_1 = hr.getContentValue("header.url");
- System.out.println("RA_SESSION_ID=" + ra_session_id );
- System.out.println("RA_URL=" + ra_url_1 );
+ System.out.println("RA_SESSION_ID=" + ra_session_id);
+ System.out.println("RA_URL=" + ra_url_1);
- // use session id to connect back to RA
+ // use session id to connect back to RA
- 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);
-
- }
+ 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 93d115fc..d666e3bf 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureSubCA.java
@@ -1,4 +1,5 @@
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
@@ -29,8 +30,7 @@ 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";
@@ -160,35 +160,29 @@ public class ConfigureSubCA
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
@@ -196,15 +190,14 @@ 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,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -217,8 +210,7 @@ public class ConfigureSubCA
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -228,40 +220,38 @@ public class ConfigureSubCA
String query_string = null;
// Software Token
- if (token_name.equalsIgnoreCase("internal"))
- {
+ if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- 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();
}
// HSM
- else
- {
+ else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- 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();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- 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);
@@ -272,26 +262,24 @@ 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 domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&sdomainName="+
+ "&sdomainName=" +
URLEncoder.encode(domain_name) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&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());
@@ -300,35 +288,33 @@ public class ConfigureSubCA
String query_string_1 = "p=4" +
"&op=next" +
- "&xml=true";
+ "&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" ;
+ "?p=5&subsystem=CA";
- String query_string = "url=" + URLEncoder.encode(subca_url);
+ 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) ;
+ "&url=" + URLEncoder.encode(subca_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -336,25 +322,24 @@ public class ConfigureSubCA
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" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ 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;
@@ -367,8 +352,8 @@ public class ConfigureSubCA
URLEncoder.encode(subsystem_name) +
"&subsystemName=" +
URLEncoder.encode(subsystem_name) +
- "&urls=0" ;
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,query_string);
+ "&urls=0";
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
// bais = new ByteArrayInputStream(hr.getHTML().getBytes());
// px.parse(bais);
@@ -377,50 +362,45 @@ 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" ;
+ "&choice=join";
- 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 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) +
+ "&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": "");
+ (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);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -430,8 +410,7 @@ public class ConfigureSubCA
return true;
}
- public boolean KeyPanel()
- {
+ public boolean KeyPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -469,23 +448,23 @@ public class ConfigureSubCA
+ "&signingalgorithm=" + signing_algorithm
+ "&keyalgorithm=" + key_algorithm;
- 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);
- 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;
@@ -494,19 +473,18 @@ 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=" +
+ 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=" +
+ 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;
@@ -515,89 +493,87 @@ 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);
+ "&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("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);
+ 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);
+ 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);
+ ca_audit_signing_cert_cert);
return true;
}
- public boolean CertificatePanel()
- {
+ public boolean CertificatePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -607,55 +583,52 @@ 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=" +
+ "&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=" +
+ "&ocsp_signing_cc=" +
+ "&sslserver=" +
+ URLEncoder.encode(server_cert_cert) +
+ "&sslserver_cc=" +
+ "&subsystem=" +
URLEncoder.encode(ca_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&audit_signing=" +
+ "&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);
+ 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" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
"&__pwdagain=" + URLEncoder.encode(backup_pwd);
- 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;
}
@@ -666,7 +639,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);
@@ -680,15 +653,13 @@ public class ConfigureSubCA
}
}
- 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,
@@ -706,19 +677,19 @@ public class ConfigureSubCA
if (crmf_request == null) {
System.out.println("ERROR: AdminCertReqPanel() cert req gen failed");
- return false;
+ 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=" +
+ "&name=" + URLEncoder.encode(agent_name) +
+ "&email=" +
URLEncoder.encode(admin_email) +
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&display=" + URLEncoder.encode("$displayStr") +
"&profileId=" + "caAdminCert" +
@@ -726,25 +697,24 @@ public class ConfigureSubCA
"&import=true" +
"&uid=" + admin_user +
"&securitydomain=" +
- URLEncoder.encode( domain_name ) +
+ URLEncoder.encode(domain_name) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
- "";
+ "";
- 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();
-
- 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;
@@ -752,14 +722,14 @@ public class ConfigureSubCA
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(cs_hostname, cs_port, admin_uri, query_string);
- 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 =
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -772,13 +742,12 @@ public class ConfigureSubCA
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;
}
@@ -787,8 +756,7 @@ public class ConfigureSubCA
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -800,15 +768,15 @@ public class ConfigureSubCA
"&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");
@@ -816,12 +784,11 @@ 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,
@@ -966,8 +933,7 @@ public class ConfigureSubCA
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureSubCA ca = new ConfigureSubCA();
// set variables
@@ -1024,7 +990,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();
@@ -1058,142 +1024,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_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_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_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);
+ 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);
+ 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",
+ 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(
+ "-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);
}
@@ -1274,24 +1240,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 =
+
+ 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_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.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 d89fb5dd..85445981 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTKS.java
@@ -1,4 +1,5 @@
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
@@ -38,8 +39,7 @@ 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";
@@ -132,7 +132,7 @@ 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;
@@ -142,31 +142,28 @@ public class ConfigureTKS
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
@@ -174,14 +171,14 @@ 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,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
"p=0&op=next&xml=true");
// parse xml here
@@ -194,8 +191,7 @@ public class ConfigureTKS
return st;
}
- public boolean TokenChoicePanel()
- {
+ public boolean TokenChoicePanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -206,10 +202,10 @@ public class ConfigureTKS
// Software Token
if (token_name.equalsIgnoreCase("internal")) {
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode("Internal Key Storage Token") +
- "";
- 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);
@@ -219,23 +215,23 @@ public class ConfigureTKS
else {
// login to hsm first
query_string = "p=2" + "&op=next" + "&xml=true" +
- "&uTokName=" +
+ "&uTokName=" +
URLEncoder.encode(token_name) +
- "&__uPasswd=" +
+ "&__uPasswd=" +
URLEncoder.encode(token_pwd) +
- "";
- 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();
-
+
// choice with token name now
query_string = "p=1" + "&op=next" + "&xml=true" +
- "&choice=" +
+ "&choice=" +
URLEncoder.encode(token_name) +
- "";
- 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);
@@ -245,24 +241,22 @@ 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 domain_url = "https://" + sd_hostname + ":" + sd_admin_port;
String query_string = "sdomainURL=" +
URLEncoder.encode(domain_url) +
- "&choice=existingdomain"+
+ "&choice=existingdomain" +
"&p=3" +
"&op=next" +
- "&xml=true";
+ "&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());
@@ -273,16 +267,15 @@ 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);
@@ -292,27 +285,25 @@ 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" ;
+ "?p=5&subsystem=TKS";
- String query_string = "url=" + URLEncoder.encode(tks_url);
+ String query_string = "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_login_uri, query_string);
String query_string_1 = "uid=" + sd_admin_name +
"&pwd=" + URLEncoder.encode(sd_admin_password) +
- "&url=" + URLEncoder.encode(tks_url) ;
+ "&url=" + URLEncoder.encode(tks_url);
- hr = hc.sslConnect(sd_hostname,sd_admin_port,sd_get_cookie_uri,
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, sd_get_cookie_uri,
query_string_1);
// get session id from security domain
@@ -320,17 +311,17 @@ public class ConfigureTKS
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" ;
+ "&xml=true";
- hr = hc.sslConnect(cs_hostname,cs_port,wizard_uri,
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri,
query_string_2);
// parse xml
@@ -341,20 +332,19 @@ 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" +
+ String query_string = "p=5" + "&op=next" + "&xml=true" +
"&subsystemName=" +
URLEncoder.encode(subsystem_name) +
- "&choice=newsubsystem" ;
+ "&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);
@@ -363,27 +353,25 @@ 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) +
+ "&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": "");
+ (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);
+ hr = hc.sslConnect(cs_hostname, cs_port, wizard_uri, query_string);
// parse xml
bais = new ByteArrayInputStream(hr.getHTML().getBytes());
@@ -393,15 +381,13 @@ 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 +
@@ -411,28 +397,28 @@ public class ConfigureTKS
"&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 +
+ "&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"+
+ "&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);
+ 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;
@@ -441,17 +427,16 @@ public class ConfigureTKS
}
}
}
-
- System.out.println("default: tks_subsystem_cert_name=" +
+
+ System.out.println("default: tks_subsystem_cert_name=" +
tks_subsystem_cert_name);
- System.out.println("default: server_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;
@@ -460,52 +445,51 @@ 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=" +
+ "&subsystem=" +
URLEncoder.encode(tks_subsystem_cert_subject_name) +
- "&sslserver=" +
+ "&sslserver=" +
URLEncoder.encode(tks_server_cert_subject_name) +
"&audit_signing=" +
URLEncoder.encode(tks_audit_signing_cert_subject_name) +
- "&urls=" +
- URLEncoder.encode(domain_url) +
- "";
+ "&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;
@@ -515,85 +499,79 @@ public class ConfigureTKS
ArrayList<String> dn_list = null;
ArrayList<String> pp_list = null;
-
String query_string = "p=10" + "&op=next" + "&xml=true" +
- "&subsystem=" +
+ "&subsystem=" +
URLEncoder.encode(tks_subsystem_cert_cert) +
- "&subsystem_cc=" +
- "&sslserver=" +
- URLEncoder.encode(server_cert_cert) +
- "&sslserver_cc=" +
+ "&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);
+ 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" +
+ "&choice=backupkey" +
"&__pwd=" + URLEncoder.encode(backup_pwd) +
- "&__pwdagain=" + URLEncoder.encode(backup_pwd);
+ "&__pwdagain=" + URLEncoder.encode(backup_pwd);
- 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 SavePKCS12Panel()
- {
+ public boolean SavePKCS12Panel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
ParseXML px = new ParseXML();
+ String query_string = "";
- 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
- 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()));
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();
@@ -601,14 +579,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;
}
@@ -616,15 +594,13 @@ 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,
@@ -640,9 +616,8 @@ 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;
}
@@ -655,9 +630,9 @@ public class ConfigureTKS
"&__pwd=" + URLEncoder.encode(admin_password) +
"&__admin_password_again=" + URLEncoder.encode(admin_password) +
"&profileId=" + "caAdminCert" +
- "&email=" +
+ "&email=" +
URLEncoder.encode(admin_email) +
- "&cert_request=" +
+ "&cert_request=" +
URLEncoder.encode(admin_cert_request) +
"&subject=" +
URLEncoder.encode(agent_cert_subject) +
@@ -665,22 +640,21 @@ public class ConfigureTKS
"&import=true" +
"&securitydomain=" +
URLEncoder.encode(domain_name) +
- "";
+ "";
- 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();
-
- 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;
@@ -688,14 +662,14 @@ public class ConfigureTKS
String query_string = "serialNumber=" + admin_serial_number +
"&importCert=" + "true" +
- "";
+ "";
+
+ hr = hc.sslConnect(sd_hostname, sd_admin_port, admin_uri, query_string);
- 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 =
+ String cert_to_import =
OSUtil.BtoA(hr.getResponseData());
System.out.println("Imported Cert=" + cert_to_import);
@@ -708,10 +682,10 @@ public class ConfigureTKS
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");
return false;
@@ -721,8 +695,7 @@ public class ConfigureTKS
return true;
}
- public boolean UpdateDomainPanel()
- {
+ public boolean UpdateDomainPanel() {
boolean st = false;
HTTPResponse hr = null;
ByteArrayInputStream bais = null;
@@ -731,21 +704,19 @@ public class ConfigureTKS
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,
@@ -806,7 +777,7 @@ public class ConfigureTKS
System.out.println("ERROR: ConfigureTKS: SubsystemPanel() failure");
return false;
}
-
+
sleep_time();
// 7. ldap connection panel
boolean disp_ldap = LdapConnectionPanel();
@@ -892,8 +863,7 @@ public class ConfigureTKS
}
}
- public static void main(String args[])
- {
+ public static void main(String args[]) {
ConfigureTKS ca = new ConfigureTKS();
// set variables
@@ -974,63 +944,63 @@ 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);
@@ -1052,44 +1022,44 @@ public class ConfigureTKS
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",
+ 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(
+ "-subsystem_name %s #CA subsystem name",
+ x_subsystem_name);
parser.addOption(
- "-tks_audit_signing_cert_subject_name %s #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);
}
@@ -1155,25 +1125,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 5273fda7..10cdc782 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/ConfigureTPS.java
@@ -1,4 +1,5 @@
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
@@ -29,1155 +30,1098 @@ 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");
+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();
- // parse xml here
+ tps_session_id = hr.getContentValue("header.session_id");
+ String tps_url_1 = hr.getContentValue("header.url");
- 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);
-
- }
+ 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 c1a9a7be..ddc356a0 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/CreateInstance.java
@@ -1,4 +1,5 @@
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
@@ -21,7 +22,6 @@ import java.net.URLEncoder;
import com.netscape.pkisilent.common.PostQuery;
-
public class CreateInstance {
private static String host;
@@ -95,7 +95,7 @@ public class CreateInstance {
adminDomain = args[8];
}
-
+
boolean st = newinstance.CreateInstance();
if (!st) {
@@ -105,10 +105,7 @@ public class CreateInstance {
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 e61af61f..70528023 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/PKISilent.java
@@ -4,57 +4,56 @@ 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 c2b927cc..de3c58bd 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParseException.java
@@ -1,4 +1,5 @@
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
@@ -18,37 +19,36 @@ 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 a205d101..f0712e38 100755
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParser.java
@@ -1,4 +1,5 @@
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
@@ -18,17 +19,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;
@@ -53,231 +54,173 @@ import java.util.Vector;
* <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 ...
*
- * DoubleHolder theta = new DoubleHolder();
- * StringHolder fileName = new StringHolder();
- * BooleanHolder debug = new BooleanHolder();
+ * static public void main(String[] args) {
+ * // create holder objects for storing results ...
*
- * // create the parser and specify the allowed options ...
+ * DoubleHolder theta = new DoubleHolder();
+ * StringHolder fileName = new StringHolder();
+ * BooleanHolder debug = new BooleanHolder();
*
- * 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 ...
+ * // create the parser and specify the allowed options ...
*
- * 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);
- * }
+ * 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 ...
+ *
+ * parser.matchAllArgs(args);
+ *
+ * // and print out the values
+ *
+ * System.out.println(&quot;theta=&quot; + theta.value);
+ * System.out.println(&quot;fileName=&quot; + fileName.value);
+ * System.out.println(&quot;debug=&quot; + 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},
- * {@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
- * (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
- * 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>
- *
+ * <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 (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 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>
+ *
* <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
- * 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.
- *
+ *
+ * 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 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 ("-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);
+ * 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);
* </pre>
- *
- * If an argument value does not lie within a specified range, an error is
- * generated.
- *
+ *
+ * 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 ("-v,--verbose %v #print lots of info");
- * parser.addOption ("-of,-outfile,-outputFile %s #output file");
+ * parser.addOption(&quot;-v,--verbose %v #print lots of info&quot;);
+ * parser.addOption(&quot;-of,-outfile,-outputFile %s #output file&quot;);
* </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 ("-file %s #file name");
+ * parser.addOption(&quot;-file %s #file name&quot;);
* </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 ("-file=%s #file name");
+ * parser.addOption(&quot;-file=%s #file name&quot;);
* </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
- * following comma. For example,
+ * 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 ("-nb=,-number ,-n%d #number of blocks");
+ * parser.addOption(&quot;-nb=,-number ,-n%d #number of blocks&quot;);
* </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 ("-position %fX3 #position of the object", pos);
+ * double[] pos = new double[3];
+ *
+ * addOption(&quot;-position %fX3 #position of the object&quot;, pos);
* </pre>
+ *
* will cause the parser to look for
+ *
* <pre>
* -position xx yy zz
* </pre>
*
- * 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.
- *
+ * 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.
+ *
* <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.
- *
- * 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
- *
+ *
+ * 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
+ *
* <pre>
- * Vector vec = new Vector(10);
- *
- * parser.addOption ("-foo %f", vec);
- * parser.matchAllArgs(args);
+ * Vector vec = new Vector(10);
+ *
+ * parser.addOption(&quot;-foo %f&quot;, 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>.
- *
+ * 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>.
+ *
* <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
+ *
+ * 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
*
* <pre>
* Usage: java argparser.SimpleExample
@@ -289,50 +232,37 @@ import java.util.Vector;
* -debug enables display of debugging info
* </pre>
*
- * 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
+ * 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
* 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 ("-theta %f #NUMBER#theta value (in degrees)",theta);
+ * parser.addOption(&quot;-theta %f #NUMBER#theta value (in degrees)&quot;, theta);
* </pre>
+ *
* instead of
+ *
* <pre>
- * parser.addOption ("-theta %f #theta value (in degrees)", theta);
+ * parser.addOption(&quot;-theta %f #theta value (in degrees)&quot;, 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);
@@ -341,13 +271,10 @@ 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}:
+ * 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}:
*
* <pre>
* int idx = 0;
@@ -365,1936 +292,1694 @@ 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.
- *
+ *
+ * {@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.
+ *
* <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;
- }
- }
- 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.");
+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");
}
- }
-
-
- 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;
- }
-}
+ // 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.");
+ }
+ }
+ }
+
+ 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 579f0f59..4a7b20e4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ArgParserTest.java
@@ -1,4 +1,5 @@
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
@@ -18,17 +19,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;
@@ -36,1537 +37,1477 @@ 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
+ * 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 c5dece11..ba10022b 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/BooleanHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,37 +19,36 @@ 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 b30259b4..453cac8b 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/CharHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,39 +19,36 @@ 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 293a9cc7..13012a64 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/DoubleHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,38 +19,36 @@ 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 0fbcc45a..b8474b53 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/FloatHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,39 +19,36 @@ 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 efd6d1bf..a94ceea1 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/IntHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,38 +19,36 @@ 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 84752d60..5656d8b8 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/LongHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,38 +19,36 @@ 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 cc8361d9..70e050fd 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/ObjectHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,37 +19,36 @@ 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 8086131b..6970d318 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/SimpleExample.java
@@ -1,4 +1,5 @@
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
@@ -18,39 +19,35 @@ 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 9b41b6a2..93736034 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringHolder.java
@@ -1,4 +1,5 @@
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
@@ -18,38 +19,36 @@ 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 4b71a0f2..bf3ea6dc 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanException.java
@@ -1,4 +1,5 @@
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,40 +20,37 @@ 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 6153f180..c6bddf26 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/argparser/StringScanner.java
@@ -1,4 +1,5 @@
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
@@ -18,626 +19,550 @@ 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++;
- }
- }
-
- 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++;
+ }
+ }
+
+ 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 925e04dc..7ba9d586 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/AutoInstaller.java
@@ -1,4 +1,5 @@
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,15 +27,12 @@ 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.
+ * 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;
@@ -54,10 +52,10 @@ public class AutoInstaller {
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";
@@ -70,7 +68,8 @@ public class AutoInstaller {
// / Constructors
- public AutoInstaller() {}
+ public AutoInstaller() {
+ }
/**
* Constructor . Takes parameter Server Root .
@@ -81,7 +80,7 @@ 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) {
@@ -109,7 +108,8 @@ 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());
}
@@ -137,23 +137,25 @@ public class AutoInstaller {
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
@@ -199,8 +201,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) {
@@ -223,7 +225,7 @@ public class AutoInstaller {
// 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) {
@@ -286,7 +288,7 @@ public class AutoInstaller {
certAdminUid = aduid;
certAdminPWD = adp;
SingleSignOnPWD = ssonpwd;
- signingCert = "raSigningCert";
+ signingCert = "raSigningCert";
certType = signingCert;
subsystems = "tks";
ra = "false";
@@ -440,7 +442,6 @@ public class AutoInstaller {
* Confiures a RA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -477,7 +478,6 @@ public class AutoInstaller {
* Confiures a OCSP Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureOCSP(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -513,7 +513,6 @@ public class AutoInstaller {
* Confiures a KRA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureKRA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -548,7 +547,6 @@ public class AutoInstaller {
* Confiures a SubCA Subsystem .Takes parameter : adminSubjectDN, adminUID, AdminPasswd, SingleSignonPasswd
*/
-
public boolean ConfigureSubCA(String adn, String aduid, String adp, String ssonpwd) {
certAdminName = adn;
certAdminUid = aduid;
@@ -594,7 +592,8 @@ 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());
}
@@ -629,7 +628,7 @@ 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");
@@ -726,13 +725,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;
@@ -978,8 +977,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");
@@ -1013,7 +1012,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)) {
@@ -1082,7 +1081,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";
@@ -1103,7 +1102,7 @@ public class AutoInstaller {
// install cert
System.out.println(
- "configuring Cert Instance : install cert :" + cert);
+ "configuring Cert Instance : install cert :" + cert);
setConfigURL();
myStringUrl = "http://" + host + ":" + adminPort + configURL;
System.out.println(myStringUrl);
@@ -1115,7 +1114,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";
@@ -1128,30 +1127,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) {
@@ -1163,19 +1162,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 += "&";
@@ -1225,7 +1224,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");
@@ -1237,7 +1236,7 @@ public class AutoInstaller {
query += "&mailCABit=" + URLEncoder.encode(mailCABit);
query += "&objectSigningCABit="
+ URLEncoder.encode(objectSigningCABit);
-
+
}
query += "&hashType=" + URLEncoder.encode(hashType);
@@ -1271,7 +1270,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";
@@ -1308,7 +1307,7 @@ public class AutoInstaller {
}
private boolean exitDeamon() {
-
+
System.out.println("configuring Cert Instance : Exit Deamon");
setDeamonURL();
String myStringUrl = "http://" + host + ":" + adminPort + configURL;
@@ -2212,12 +2211,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();
}
@@ -2230,7 +2229,6 @@ public class AutoInstaller {
// - 1 Configured and server Alive
// - 0 Configured bur could not sart server
-
AutoInstaller t = new AutoInstaller();
System.out.println(args.length);
@@ -2239,13 +2237,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 {
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 a3ceec31..99487a8f 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/BaseState.java
@@ -1,4 +1,5 @@
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
@@ -17,40 +18,37 @@ 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.
+ * 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) {
ldaphost = h;
@@ -63,8 +61,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,7 +77,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() {
@@ -98,10 +96,9 @@ 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();
@@ -114,6 +111,7 @@ 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 94c57a62..5a933a22 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSConfig.java
@@ -1,4 +1,5 @@
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
@@ -20,20 +21,17 @@ 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
+ * 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)
*/
-
public CMSConfig(String confFile) {
CMSConfigFile = confFile;
System.out.println(CMSConfigFile);
@@ -57,7 +55,7 @@ public class CMSConfig extends ServerInfo {
}
/**
- * Saves the config file
+ * Saves the config file
**/
public void saveCMSConfig() {
@@ -85,7 +83,6 @@ public class CMSConfig extends ServerInfo {
// Authentication
-
// Enable DirectoryBased Authentication
/**
* Takes parameters : secureConnection( true/false), basedn, ldaphostname, lapdaportnumber ( in case of secured connection give ldap secured port)
@@ -560,7 +557,7 @@ public class CMSConfig extends ServerInfo {
// s.EnableDirEnrollment(secureC);
s.saveCMSConfig();
-
+
}// end of function main
} // 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 0687bc2a..d163a7f1 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSInstance.java
@@ -1,4 +1,5 @@
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,7 +26,6 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
-
public class CMSInstance {
private int i;
@@ -34,10 +34,9 @@ public class CMSInstance {
/**
* CMS Test framework .
- * This class Creates and Removes a CMS server instance
+ * 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"
*/
@@ -101,7 +100,7 @@ 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");
BufferedWriter awriter;
@@ -152,12 +151,12 @@ public class CMSInstance {
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" };
+ "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;
@@ -192,7 +191,7 @@ public class CMSInstance {
+ startURL;
System.out.println(myStringUrl);
-
+
String query = "serverRoot=" + URLEncoder.encode(serverRoot);
query += "&instanceID=" + URLEncoder.encode(instanceID);
@@ -205,7 +204,7 @@ public class CMSInstance {
PostQuery sm = new PostQuery(myStringUrl, AdminDN, AdminDNPW, query);
return (sm.Send());
-
+
}
public boolean RemoveInstance() {
@@ -214,11 +213,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();
@@ -233,15 +232,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[]) {
@@ -250,38 +249,38 @@ 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.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.exit(0);
}
@@ -289,11 +288,11 @@ public class CMSInstance {
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);
}
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 038ec42f..643f706a 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSLDAP.java
@@ -1,4 +1,5 @@
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
@@ -31,15 +32,13 @@ 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.
+ * 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;
@@ -47,7 +46,8 @@ public class CMSLDAP {
private LDAPConnection conn = new LDAPConnection();
- public CMSLDAP() {}
+ public CMSLDAP() {
+ }
/**
* Constructor. Takes parametes ldaphost, ldapport
@@ -68,7 +68,7 @@ public class CMSLDAP {
}
/**
- * Connect to ldap server
+ * Connect to ldap server
*/
public boolean connect() {
@@ -100,11 +100,11 @@ public class CMSLDAP {
/**
* 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);
@@ -135,11 +135,9 @@ 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);
@@ -175,9 +173,9 @@ public class CMSLDAP {
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson"}));
+ 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));
@@ -225,7 +223,7 @@ public class CMSLDAP {
val += ',';
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -258,19 +256,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) {
try {
X509Certificate cert = getXCertificate(certpack);
-
+
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson", "cmsuser"}));
+ 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));
@@ -301,7 +299,7 @@ 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) {
@@ -310,10 +308,10 @@ public class CMSLDAP {
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add(
- new LDAPAttribute("objectclass",
- new String[] {
- "top", "person", "organizationalPerson",
- "inetorgperson", "cmsuser"}));
+ 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));
@@ -345,7 +343,7 @@ 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) {
@@ -370,7 +368,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) {
@@ -415,7 +413,7 @@ public class CMSLDAP {
}
/**
- * Will trun of SSL in LDAP server
+ * Will trun of SSL in LDAP server
**/
public boolean TurnOffSSL() {
@@ -430,7 +428,6 @@ public class CMSLDAP {
// conn.delete("cn=RSA,cn=encryption,cn=config");
-
mods.add(LDAPModification.REPLACE, ssl3);
mods.add(LDAPModification.DELETE, ssl3ciphers);
mods.add(LDAPModification.DELETE, kfile);
@@ -464,7 +461,7 @@ public class CMSLDAP {
/**
* 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";
@@ -472,8 +469,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);
@@ -481,7 +478,7 @@ 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");
@@ -500,7 +497,7 @@ 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);
@@ -532,7 +529,7 @@ public class CMSLDAP {
attrSet.add(
new LDAPAttribute("objectclass",
- new String[] { "top", "nsEncryptionModule"}));
+ new String[] { "top", "nsEncryptionModule" }));
attrSet.add(new LDAPAttribute("cn", "RSA"));
attrSet.add(
new LDAPAttribute("nsssltoken", "internal (software)"));
@@ -561,7 +558,8 @@ public class CMSLDAP {
String PASSWORD = args[3];
String BASEDN = args[4];
- String s = "MIICFzCCAYCgAwIBAgIBBjANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVz\ndDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTEyMTUx\nMzZaFw0wNDA0MTAwOTQ2NTVaMFwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNTU0wxHTAbBgNVBAsT\nFHNzbHRlc3QxMDUwMDk3ODkzNzQ1MSAwHgYDVQQDExdqdXBpdGVyMi5uc2NwLmFvbHR3Lm5ldDBc\nMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDCsCTIIQ+bJMfPHi6kwa7HF+/xSTVHcpZ5zsodXsNWjPlD\noRu/5KAO8NotfwGnYmALWdYnqXCF0q0gkaJQalQTAgMBAAGjRjBEMA4GA1UdDwEB/wQEAwIFoDAR\nBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUzxZkSySZT/Y3SxGMEiNyHnLUOPAwDQYJKoZI\nhvcNAQEEBQADgYEALtpqMOtZt6j5KlghDFgdg/dvf36nWiZwC1ap6+ka22shLkA/RjmOix97btzT\nQ+8LcmdkAW5iap4YbtrCu0wdN6IbIEXoQI1QGZBoKO2o02utssXANmTnRCyH/GX2KefQlp1NSRj9\nZNZ+GRT2Qk/8G5Ds9vVjm1I5+/AkzI9jS14=";
+ String s =
+ "MIICFzCCAYCgAwIBAgIBBjANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVz\ndDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTEyMTUx\nMzZaFw0wNDA0MTAwOTQ2NTVaMFwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNTU0wxHTAbBgNVBAsT\nFHNzbHRlc3QxMDUwMDk3ODkzNzQ1MSAwHgYDVQQDExdqdXBpdGVyMi5uc2NwLmFvbHR3Lm5ldDBc\nMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDCsCTIIQ+bJMfPHi6kwa7HF+/xSTVHcpZ5zsodXsNWjPlD\noRu/5KAO8NotfwGnYmALWdYnqXCF0q0gkaJQalQTAgMBAAGjRjBEMA4GA1UdDwEB/wQEAwIFoDAR\nBglghkgBhvhCAQEEBAMCBkAwHwYDVR0jBBgwFoAUzxZkSySZT/Y3SxGMEiNyHnLUOPAwDQYJKoZI\nhvcNAQEEBQADgYEALtpqMOtZt6j5KlghDFgdg/dvf36nWiZwC1ap6+ka22shLkA/RjmOix97btzT\nQ+8LcmdkAW5iap4YbtrCu0wdN6IbIEXoQI1QGZBoKO2o02utssXANmTnRCyH/GX2KefQlp1NSRj9\nZNZ+GRT2Qk/8G5Ds9vVjm1I5+/AkzI9jS14=";
s = "-----BEGIN CERTIFICATE-----" + "\n" + s + "\n"
+ "-----END CERTIFICATE-----\n";
@@ -590,7 +588,7 @@ 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))
// {System.out.println("Trusted MAnager user Could not be add ");}
@@ -609,4 +607,3 @@ 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 bae3e420..c79174f6 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSProperties.java
@@ -1,4 +1,5 @@
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
@@ -40,45 +41,29 @@ 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.
* <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
- * 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.
+ * 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 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.
* <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.
+ * <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>
- *
- * @author Arthur van Hoff
- * @author Michael McCloskey
+ *
+ * @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
@@ -88,7 +73,7 @@ class CMSProperties extends Hashtable<String,String> {
/**
* A property list that contains default values for any keys not
* found in this property list.
- *
+ *
* @serial
*/
protected CMSProperties defaults;
@@ -102,8 +87,8 @@ 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;
@@ -113,11 +98,11 @@ class CMSProperties extends Hashtable<String,String> {
* 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);
@@ -135,75 +120,54 @@ class CMSProperties extends Hashtable<String,String> {
* 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).
+ * 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).
* <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.
+ * 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.
* <p>
- * As an example, each of the following four lines specifies the key
- * <code>"Truth"</code> and the associated element value
- * <code>"Beauty"</code>:
+ * 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>"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.
+ *
+ * <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.
* <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.
+ *
+ * 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.
*/
public synchronized void load(InputStream inStream) throws IOException {
@@ -235,8 +199,7 @@ class CMSProperties extends Hashtable<String,String> {
for (startIndex = 0; startIndex < nextLine.length(); startIndex++) {
if (whiteSpaceChars.indexOf(
- nextLine.charAt(startIndex))
- == -1) {
+ nextLine.charAt(startIndex)) == -1) {
break;
}
}
@@ -277,8 +240,7 @@ 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;
}
}
@@ -286,16 +248,14 @@ class CMSProperties extends Hashtable<String,String> {
// Skip over one non whitespace key value separators if any
if (valueIndex < len) {
if (strictKeyValueSeparators.indexOf(
- line.charAt(valueIndex))
- != -1) {
+ 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++;
@@ -418,7 +378,7 @@ class CMSProperties extends Hashtable<String,String> {
switch (aChar) {
case ' ':
- if (x == 0 || escapeSpace) {
+ if (x == 0 || escapeSpace) {
outBuffer.append('\\');
}
@@ -472,70 +432,49 @@ class CMSProperties extends Hashtable<String,String> {
/**
* 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.
+ * 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.
* <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
- * identifying comment.
+ * 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 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.
+ * 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.
* <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>&#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
- * preceding <code>\</code>. The key and value characters <code>#</code>,
- * <code>!</code>, <code>=</code>, and <code>:</code> are written with a
- * preceding slash to ensure that they are properly loaded.
+ * 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>&#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 preceding <code>\</code>. The key and value characters <code>#</code>, <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
- * 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>.
+ * 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>.
*/
public synchronized void store(OutputStream out, String header)
- throws IOException {
+ throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
@@ -544,8 +483,8 @@ 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);
@@ -566,17 +505,16 @@ class CMSProperties extends Hashtable<String,String> {
/**
* Searches for the property with the specified key in this property list.
* 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
+ * 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
*/
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)
@@ -588,13 +526,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);
@@ -605,11 +543,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>();
@@ -621,8 +559,8 @@ 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.
+ *
+ * @param out an output stream.
*/
public void list(PrintStream out) {
out.println("-- listing properties --");
@@ -630,8 +568,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) + "...";
@@ -643,11 +581,11 @@ 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
+ *
+ * @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
@@ -659,8 +597,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) + "...";
@@ -671,6 +609,7 @@ 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) {
@@ -678,7 +617,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));
}
@@ -686,7 +625,8 @@ 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)];
@@ -694,7 +634,7 @@ class CMSProperties extends Hashtable<String,String> {
/** 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'
+ '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 593de383..4b6c75ba 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CMSTask.java
@@ -1,4 +1,5 @@
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,10 +25,9 @@ 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
+ * This class starts and stops CS server from command line
*/
public class CMSTask {
@@ -38,7 +38,7 @@ public class CMSTask {
private Process p = null;
/**
- * Constructor . Takes CMS server root as parameter
+ * Constructor . Takes CMS server root as parameter
* for example (/export/qa/cert-jupiter2)
**/
@@ -63,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
@@ -175,7 +175,7 @@ public class CMSTask {
// set variables
serverRoot = x_instance_root.value;
operation = x_operation.value;
-
+
boolean st = prof.task();
if (!st) {
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 c636b0a1..9599eb6d 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/CertificateRecord.java
@@ -1,4 +1,5 @@
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
@@ -17,8 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
-
public class CertificateRecord {
public String revokedOn = null;
@@ -42,7 +41,4 @@ 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 46bd9664..9881aa2c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ComCrypto.java
@@ -1,4 +1,5 @@
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
@@ -64,13 +65,11 @@ 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.
*/
-
public class ComCrypto {
private String cdir, certnickname, keysize, keytype, tokenpwd;
@@ -98,19 +97,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)
+ *
* @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;
@@ -190,10 +189,9 @@ public class ComCrypto {
}
/**
- * Finds and returns Certificate . Takes certificatenickname as parameter.
+ * Finds and returns Certificate . Takes certificatenickname as parameter.
*/
-
public X509Certificate findCert(String certname) {
try {
@@ -212,7 +210,6 @@ public class ComCrypto {
* Imports a certificate to Certificate Database. Takes certificate and nickname as parameters.
*/
-
public boolean importCert(X509Certificate xcert, String nickname) {
try {
@@ -235,7 +232,6 @@ public class ComCrypto {
* 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 +239,7 @@ public class ComCrypto {
String tmp = normalize(cpack);
- if (DBlogin) {
+ if (DBlogin) {
System.out.println("Already logged into to DB");
}
@@ -272,10 +268,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");
}
@@ -296,7 +292,6 @@ public class ComCrypto {
* Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
*/
-
public String normalize(String s) {
String val = "";
@@ -321,7 +316,6 @@ public class ComCrypto {
* Normalizes a given certificate string . Removes the extra \\ in the certificate returned by CMS server.
*/
-
public String normalizeForLDAP(String s) {
String val = "";
@@ -346,7 +340,6 @@ public class ComCrypto {
* Convert to pkcs7 format
*/
-
public String pkcs7Convertcert(String s) {
String val = "";
@@ -396,14 +389,13 @@ 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 +431,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,14 +499,14 @@ 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) {
+ } catch (Exception e) {
// it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
@@ -525,17 +517,17 @@ public class ComCrypto {
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) {
@@ -548,7 +540,7 @@ public class ComCrypto {
// 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();
@@ -556,7 +548,7 @@ public class ComCrypto {
kg.initialize(key_len);
// 1st key pair
- pair = kg.genKeyPair();
+ pair = kg.genKeyPair();
// create CRMF
CertTemplate certTemplate = new CertTemplate();
@@ -565,7 +557,7 @@ 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);
}
@@ -575,7 +567,7 @@ public class ComCrypto {
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)));
@@ -583,24 +575,24 @@ public class ComCrypto {
CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null);
SEQUENCE s1 = new SEQUENCE();
-
+
// 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();
// String Req1 = encoder.encodeBuffer(encoded);
@@ -611,7 +603,7 @@ public class ComCrypto {
System.out.println("CRMF_REQUEST = " + CRMF_REQUEST);
- } catch (Exception e) {
+ } catch (Exception e) {
System.out.println("ERROR: " + e.toString());
e.printStackTrace();
return null;
@@ -636,9 +628,9 @@ public class ComCrypto {
try {
// Step 1. initialize crypto Manager
- try {
+ try {
CryptoManager.initialize(cdir);
- } catch (Exception e) {
+ } catch (Exception e) {
// it is ok if it is already initialized
System.out.println("INITIALIZATION ERROR: " + e.toString());
System.out.println("cdir = " + cdir);
@@ -648,18 +640,18 @@ public class ComCrypto {
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) {
@@ -669,7 +661,7 @@ public class ComCrypto {
token.initPassword(password, password);
}
}
-
+
// Key Pair Generation
KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
Integer x = new Integer(keysize);
@@ -686,7 +678,7 @@ 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();
@@ -742,7 +734,7 @@ public class ComCrypto {
seq);
// Adding proof of possesion data
- byte popdata[] = { 0x0, 0x3, 0x0};
+ byte popdata[] = { 0x0, 0x3, 0x0 };
ProofOfPossession pop = ProofOfPossession.createKeyEncipherment(
POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3)));
@@ -754,19 +746,19 @@ public class ComCrypto {
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);
@@ -781,7 +773,7 @@ public class ComCrypto {
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
-
+
return CRMF_REQUEST;
}
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 6be4daf4..8071dcb2 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Con2Agent.java
@@ -1,4 +1,5 @@
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
@@ -35,7 +36,6 @@ 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.
@@ -51,18 +51,19 @@ 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;
@@ -168,7 +169,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -184,7 +185,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");
@@ -239,12 +240,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();
- if (token.isLoggedIn()) {
+ if (token.isLoggedIn()) {
System.out.println("Con2Agent: Logged in incorrect");
}
@@ -256,12 +257,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) {
@@ -276,7 +277,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
e.printStackTrace();
return false;
}
-
+
}
public boolean Send_withGET() {
@@ -285,7 +286,7 @@ public class Con2Agent implements SSLClientCertificateSelectionCallback,
try {
- if (!loginCertDB()) {
+ if (!loginCertDB()) {
return false;
}
@@ -297,7 +298,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);
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 59820fe7..f82c7c8f 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/DirEnroll.java
@@ -1,4 +1,5 @@
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
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,15 +29,12 @@ 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;
@@ -53,7 +50,8 @@ 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) {
@@ -63,6 +61,7 @@ public class DirEnroll extends TestClient {
/**
* Constructor. Takes hostname , EESSLportnumber as parameter
* <p>
+ *
* @param hostname
* @param portnumber
*/
@@ -73,8 +72,9 @@ 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
@@ -82,7 +82,6 @@ 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) {
host = hs;
@@ -99,15 +98,15 @@ public class DirEnroll extends TestClient {
// 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() {
@@ -115,16 +114,16 @@ 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() {
@@ -134,7 +133,7 @@ public class DirEnroll extends TestClient {
cCrypt.setKeySize(keysize);
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
-
+
cCrypt.setDebug(debug);
cCrypt.setGenerateRequest(true);
if (!cCrypt.generateRequest()) {
@@ -147,7 +146,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);
}
@@ -157,10 +156,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() {
@@ -310,7 +309,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")) {
@@ -352,13 +351,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");
@@ -376,7 +375,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");
}
@@ -412,7 +411,7 @@ public class DirEnroll extends TestClient {
queryStrBuf.append("&l=");
queryStrBuf.append(URLEncoder.encode(L));
- queryStrBuf.append("&email=true");
+ queryStrBuf.append("&email=true");
}
@@ -423,7 +422,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");
}
@@ -432,25 +431,25 @@ 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) {
+ if (st) {
System.out.println(
t.getAuthenticator() + " based enrollment successfull. ");
System.exit(1);
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 79be5c35..22c1c402 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ParseXML.java
@@ -1,4 +1,5 @@
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
@@ -31,7 +32,6 @@ import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-
public class ParseXML {
Document dom = null;
@@ -77,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);
@@ -107,9 +107,10 @@ 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);
@@ -132,7 +133,7 @@ public class ParseXML {
try {
// get the root elememt
Element docEle = dom.getDocumentElement();
-
+
// get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName(first);
@@ -163,10 +164,8 @@ 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 87fcf500..64e49d90 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/PostQuery.java
@@ -1,4 +1,5 @@
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
@@ -33,8 +34,6 @@ import com.netscape.osutil.OSUtil;
* 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,10 +44,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;
@@ -82,7 +81,7 @@ public class PostQuery {
try {
- BufferedReader mbufferedReader = null;
+ BufferedReader mbufferedReader = null;
URL myUrl = new URL(URLString);
String userPassword = adminID + ":" + adminPWD;
@@ -103,7 +102,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);
@@ -112,7 +111,7 @@ public class PostQuery {
os.writeBytes(postQuery);
os.flush();
os.close();
-
+
InputStream Content = (InputStream) URLCon.getInputStream();
System.out.println("Configuring Cert Instance : Return Response");
@@ -127,12 +126,12 @@ public class PostQuery {
if (st) {
break;
}
- }
+ }
URLCon.disconnect();
} // 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 9ddc9970..0cb08577 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Request.java
@@ -1,4 +1,5 @@
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
@@ -17,21 +18,17 @@ 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
*/
-
public class Request extends TestClient {
private String validityperiod;
@@ -63,18 +60,19 @@ public class Request extends TestClient {
/**
* 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
*/
@@ -85,9 +83,10 @@ 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
@@ -97,13 +96,12 @@ 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) {
host = h;
ports = p;
@@ -142,7 +140,7 @@ public class Request extends TestClient {
}
/**
- * Set Agent Cert nick name
+ * Set Agent Cert nick name
*/
public void setAgentCertName(String s) {
certnickname = s;
@@ -150,7 +148,8 @@ public class Request extends TestClient {
/**
* List all pending enrollment request. Takes parameters fromRequestNumber,toRequestNumber
- * @param fromrequest number
+ *
+ * @param fromrequest number
* @param endrequestnumber.
*/
@@ -165,11 +164,11 @@ public class Request extends TestClient {
/**
* List all pending request. Takes parameters fromRequestNumber,toRequestNumber
- * @param fromrequest number
+ *
+ * @param fromrequest number
* @param endrequestnumber.
*/
-
public Vector<String> ListAllRequests(String fromRequestNumber, String toRequestNumber) {
reqState = "showAll";
reqType = "enrollment";
@@ -181,10 +180,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";
@@ -202,7 +201,8 @@ public class Request extends TestClient {
/**
* Approve profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ *
+ * @param request number
*/
public int ApproveProfileRequests(String RequestNumber) {
@@ -222,7 +222,7 @@ public class Request extends TestClient {
}
public boolean Approve_cadualcert_Profile_Request(String RequestNumber, String name) {
-
+
approveseqnum = RequestNumber;
approveseqnumFrom = RequestNumber;
approveseqnumTo = RequestNumber;
@@ -237,7 +237,7 @@ public class Request extends TestClient {
buildquery();
- if (!Send()) {
+ if (!Send()) {
System.out.println("Error: Approving request " + approveseqnum);
return false;
}
@@ -248,10 +248,10 @@ public class Request extends TestClient {
/**
* Reject profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ *
+ * @param request number
*/
-
public int RejectProfileRequests(String RequestNumber) {
approveseqnum = RequestNumber;
@@ -270,7 +270,8 @@ public class Request extends TestClient {
/**
* Cancel profile based pending enrollment request. Takes parameters RequestNumber
- * @param request number
+ *
+ * @param request number
*/
public int CancelProfileRequests(String RequestNumber) {
@@ -354,14 +355,14 @@ 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++;
- }
-
+ }
+
}
}
@@ -481,7 +482,6 @@ 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(
@@ -587,17 +587,17 @@ public class Request extends TestClient {
"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;
@@ -627,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;
@@ -645,7 +645,7 @@ public class Request extends TestClient {
break;
case 3:
- st = approveRequestStatus(s);
+ st = approveRequestStatus(s);
break;
case 4:
@@ -665,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);
@@ -685,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;
@@ -699,7 +699,7 @@ public class Request extends TestClient {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -719,7 +719,7 @@ public class Request extends TestClient {
if (csrRequestorPhone != null) {
query += "&csrRequestorPhone=" + csrRequestorPhone;
}
-
+
if (csrRequestorEmail != null) {
query += "&csrRequestorEmail=" + csrRequestorEmail;
}
@@ -746,7 +746,7 @@ public class Request extends TestClient {
query += "&certTypeSSLServer=" + servercert;
}
- if (emailcert.equals("true")) {
+ if (emailcert.equals("true")) {
query += "&certTypeEmail=" + emailcert;
}
@@ -764,7 +764,7 @@ public class Request extends TestClient {
Integer x = new Integer(validityperiod);
validperiod = x.intValue();
- } else {
+ } else {
validperiod = 180;
}
@@ -872,18 +872,18 @@ public class Request extends TestClient {
+ "&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
+ "&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"
@@ -892,7 +892,7 @@ public class Request extends TestClient {
+ "&op=approve" + "&submit=submit";
}
-
+
}
private void readProperties() {
@@ -968,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() {
@@ -989,7 +989,7 @@ public class Request extends TestClient {
return false;
}
- if (approveseqnum.length() > 0) {
+ if (approveseqnum.length() > 0) {
if (seqNum.contains(approveseqnum)) {
seqNum.removeAllElements();
seqNum.addElement(approveseqnum);
@@ -1002,7 +1002,7 @@ public class Request extends TestClient {
System.out.println(
" Seq num not specified . Approving all pending request From : "
+ approveseqnumFrom + " To : " + approveseqnumTo);
- }
+ }
boolean flag = true;
@@ -1023,44 +1023,43 @@ public class Request extends TestClient {
i++;
continue;
}
-
+
if (debug) {
System.out.println(
csrRequestorName + " " + csrRequestorPhone + " "
- + csrRequestorEmail + " " + requestID + " "
- + subject);
+ + csrRequestorEmail + " " + requestID + " "
+ + subject);
}
// Now for pending status - approve the request
reqtype = 3;
buildquery();
if (!Send()) {
System.out.println(
- "Error: Approving request " + approveseqnum);
+ "Error: Approving request " + approveseqnum);
i++;
continue;
}
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();
}
@@ -1090,7 +1089,7 @@ public class Request extends TestClient {
} else {
return 0;
}
- } else {
+ } else {
return -1;
}
@@ -1103,11 +1102,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]);
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 c353c4ae..617fb583 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/ServerInfo.java
@@ -1,4 +1,5 @@
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
@@ -23,13 +24,11 @@ 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..
*/
-
public class ServerInfo {
public String serverRoot, instanceRoot, instanceID;
@@ -45,7 +44,8 @@ public class ServerInfo {
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.
@@ -61,7 +61,6 @@ 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 .
*/
-
public ServerInfo(String sroot, String instRoot) {
serverRoot = sroot;
instanceRoot = instRoot;
@@ -82,10 +81,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;
}
}
@@ -98,8 +97,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() {
@@ -151,12 +150,12 @@ public class ServerInfo {
// 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() {
@@ -165,7 +164,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 {
@@ -209,11 +208,11 @@ public class ServerInfo {
} else if (token.equals(" port=")) {
index2 = PORT;
}
-
+
if (index1 != 5 && index2 == IP && !token.equals(" ip=")) {
String ip = token;
} else if (index2 == PORT && !token.equals(" port=")) {
-
+
switch (index1) {
case 1:
CMSAgentPort = token;
@@ -232,7 +231,7 @@ public class ServerInfo {
break;
default:
- break;
+ break;
}
@@ -247,10 +246,11 @@ public class ServerInfo {
if (in != null) {
try {
in.close();
- } catch (Exception ex) {}
+ } catch (Exception ex) {
+ }
}
}
- }
+ }
private String stripSpace(String s) {
@@ -260,7 +260,7 @@ public class ServerInfo {
if ((s.charAt(i) == ' ')) {
i++;
continue;
- } else {
+ } else {
val += s.charAt(i);
}
}
@@ -280,7 +280,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;
@@ -305,7 +305,7 @@ public class ServerInfo {
}
}
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -333,7 +333,7 @@ public class ServerInfo {
ServerCertNickName = "Server-Cert cert-" + instanceID;
}
IDBPort = CMSprops.getProperty("internaldb.ldapconn.port");
-
+
fis.close();
} catch (Exception e) {
System.out.println("exception " + e.getMessage());
@@ -347,17 +347,17 @@ 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
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 d711e409..b0840c90 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/TestClient.java
@@ -1,4 +1,5 @@
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,15 +27,11 @@ 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.
*/
-
-
public class TestClient implements SSLCertificateApprovalCallback {
public int port;
@@ -54,16 +51,16 @@ public class TestClient implements SSLCertificateApprovalCallback {
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;
@@ -82,11 +79,11 @@ 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"};
+ "Unauthorized Access", "Server Error",
+ "Not Found", "Generic Unauthorized" };
public boolean approve(X509Certificate x509, SSLCertificateApprovalCallback.ValidityStatus status) {
SSLServerCert = x509;
@@ -95,22 +92,21 @@ public class TestClient implements SSLCertificateApprovalCallback {
// Constructor
-
public TestClient() {
keysize = "1024";
keytype = "RSA";
}
/**
- * 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");
@@ -175,7 +171,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
* This function returns true if you choose to executeCleanupTests
*/
-
public boolean executeCleanupTests() {
if (cleanupTests == null) {
@@ -214,7 +209,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
public String GetLDAPDNPW() {
return ldaprootDNPW;
- }
+ }
public String GetLDAPBASE() {
return ldapBaseSuffix;
@@ -298,10 +293,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) {
@@ -352,7 +347,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
ErrorDetail = line.substring(ret + ("errorReason=").length());
return true;
}
-
+
return false;
}
@@ -372,7 +367,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
- public String ReadEnv(String str) {
+ public String ReadEnv(String str) {
try {
Process p = null;
Runtime r = Runtime.getRuntime();
@@ -467,7 +462,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);
@@ -501,7 +496,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) {
@@ -533,14 +528,12 @@ public class TestClient implements SSLCertificateApprovalCallback {
*******************************************************************
*/
-
/*
********************************************************************
* To Test AutoInstaller
*******************************************************************
*/
-
/*
AutoInstaller a = new AutoInstaller(t.GetServerRoot());
@@ -589,12 +582,10 @@ public class TestClient implements SSLCertificateApprovalCallback {
******************************************************
*/
-
-
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());
@@ -604,8 +595,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());
@@ -641,7 +632,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
pr.clientCertEnroll();
*/
-
/* ****************************************************************
* OCSP Client stuff
************************************************************
@@ -655,7 +645,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
ocspclient.SendOCSPRequest();
*/
-
/*
*****************************************************
* Test CRMFcleint and KRA REcovery and Archival
@@ -668,7 +657,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
*********************************************************
*/
-
/* Retrieval rtr = new Retrieval(s.GetHostName(),s.GetEESSLPort());
rtr.getCACert();
System.out.println("CA Cert chain" + rtr.getCert());
@@ -682,7 +670,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
ocspAgent.addCA();
*/
-
/*
***************************************************************
Submit Profile based request
@@ -747,8 +734,8 @@ public class TestClient implements SSLCertificateApprovalCallback {
*************************************************************
* Example to Connect oto Config Directory port
*************************************************************
- */
-
+ */
+
/*
CMSLDAP cmsldap = new CMSLDAP(s.GetHostName(),s.GetConfigLDAPPort(),t.GetLDAPDN(),t.GetLDAPDNPW());
if(cmsldap.connect())
@@ -762,14 +749,14 @@ public class TestClient implements SSLCertificateApprovalCallback {
*/
-
/*
*************************************************************
* Example to Submit a CRMFCleint request to CA
*************************************************************
- */
+ */
- String TransportCert = "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTgyMjMwMDhaFw0wNDA0MTcxMDI2MDhaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAN6sQ3mSU8mL6i6gTZIXDLzOZPhYOkQLpnJjit5hcPZ0JMn0CQVXo4QjKN1xvuZv8qVlZoQw9czmzp/knTa0sCDgFKd0r+u0TnLeZkJMSimgFnma9CnChlaDHnBd8Beu4vyaHmo7rJ0xA4etn7HjhmKbaQZOcv/aP0SW9JXRga7ZAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBSC3fsQHb7fddr2vL0UdkM2dAmUWzANBgkqhkiG9w0BAQQFAAOBgQBkAGbgd9HIqwoLKAr+V6bj9oWesDmDH80gPPxj10qyWSQYIs8PofOs/75yGS9nxhydtgSMFoBgCPdroUI31kZQQlFzxtudGoKD+5MWSXho79XzPwpjheOBYgpX6ch+L4tMLFDpqeraB1yZESO5EEeKm20DGVBOKVWxHhddO1BenA==";
+ String TransportCert =
+ "MIICJTCCAY6gAwIBAgIBBTANBgkqhkiG9w0BAQQFADBDMRswGQYDVQQKExJhY2NlcHRhY25ldGVzdDEwMjQxFzAVBgNVBAsTDmFjY2VwdGFuY2V0ZXN0MQswCQYDVQQDEwJjYTAeFw0wMzA0MTgyMjMwMDhaFw0wNDA0MTcxMDI2MDhaMDkxETAPBgNVBAoTCHRlc3QxMDI0MRcwFQYDVQQLEw5hY2NlcHRhbmNldGVzdDELMAkGA1UEAxMCcmEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAN6sQ3mSU8mL6i6gTZIXDLzOZPhYOkQLpnJjit5hcPZ0JMn0CQVXo4QjKN1xvuZv8qVlZoQw9czmzp/knTa0sCDgFKd0r+u0TnLeZkJMSimgFnma9CnChlaDHnBd8Beu4vyaHmo7rJ0xA4etn7HjhmKbaQZOcv/aP0SW9JXRga7ZAgMBAAGjMzAxMA4GA1UdDwEB/wQEAwIFIDAfBgNVHSMEGDAWgBSC3fsQHb7fddr2vL0UdkM2dAmUWzANBgkqhkiG9w0BAQQFAAOBgQBkAGbgd9HIqwoLKAr+V6bj9oWesDmDH80gPPxj10qyWSQYIs8PofOs/75yGS9nxhydtgSMFoBgCPdroUI31kZQQlFzxtudGoKD+5MWSXho79XzPwpjheOBYgpX6ch+L4tMLFDpqeraB1yZESO5EEeKm20DGVBOKVWxHhddO1BenA==";
/*
CRMFClient CrmfClient = new CRMFClient(s.GetHostName(),s.GetEEPort());
@@ -782,7 +769,7 @@ public class TestClient implements SSLCertificateApprovalCallback {
if(!CrmfClient.Enroll())
{System.out.println("CRMFClient : could not submit request");}
*/
-
+
/* KRA Agent list archived request */
/* ServerInfo KRAsvrInfo = new ServerInfo(t.GetServerRoot());
@@ -803,7 +790,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
}
*/
-
// cmsldap.disconnect();
@@ -900,7 +886,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
*/
-
/*
*************************************************************
* Example agent ro revoke request
@@ -951,8 +936,6 @@ public class TestClient implements SSLCertificateApprovalCallback {
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 cd6ebd87..216465a4 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/UserEnroll.java
@@ -1,4 +1,5 @@
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
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@@ -29,15 +29,12 @@ 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>
+ * <P>
*/
-
public class UserEnroll extends TestClient {
private int i;
@@ -46,15 +43,14 @@ public class UserEnroll extends TestClient {
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;
@@ -63,10 +59,10 @@ 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;
}
@@ -75,11 +71,11 @@ public class UserEnroll extends TestClient {
* 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;
@@ -115,7 +111,7 @@ 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) {
@@ -158,7 +154,7 @@ public class UserEnroll extends TestClient {
public boolean enroll_load() {
buildquery();
setStatusString("");
- return(Send());
+ return (Send());
}
private boolean pkcs10() {
@@ -171,7 +167,7 @@ public class UserEnroll extends TestClient {
cCrypt.setKeyType(keytype);
cCrypt.setTokenPWD(tokenpwd);
cCrypt.setDebug(true);
- if (pkcs10request != null) {
+ if (pkcs10request != null) {
cCrypt.setGenerateRequest(false);
cCrypt.loginDB();
} else {
@@ -190,12 +186,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);
}
@@ -222,7 +218,7 @@ public class UserEnroll extends TestClient {
try {
- if (debug) {
+ if (debug) {
System.out.println("Step 3 : Socket initialize");
}
@@ -268,7 +264,7 @@ public class UserEnroll extends TestClient {
if (line.indexOf("fixed.requestId = ") != -1) {
requestId = line.substring("fixed.requestId = ".length() + 1,
line.indexOf(";") - 1);
- }
+ }
if (getError(line)) {
st = false;
@@ -296,7 +292,7 @@ public class UserEnroll extends TestClient {
}
return st;
-
+
}
private void buildquery() {
@@ -331,12 +327,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));
}
@@ -344,7 +340,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);
@@ -412,7 +408,7 @@ public class UserEnroll extends TestClient {
query = queryStrBuf.toString();
System.out.println(query);
- queryStrBuf = null;
+ queryStrBuf = null;
}
public int getRequestId() {
@@ -430,16 +426,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() {
@@ -493,12 +489,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[]) {
@@ -512,7 +508,7 @@ public class UserEnroll extends TestClient {
"secret12", "true", "1024", "RSA", "rn", "re", "client");
e.clientCertEnroll();
-
+
/* if ( args.length < 1)
{
System.out.println("Usage : propertiesfile");
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 3d90c841..9aaf6c4d 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/Utilities.java
@@ -1,4 +1,5 @@
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
@@ -79,7 +80,7 @@ public class Utilities {
StringBuffer buf = new StringBuffer();
int end = token.length();
int begin = 0;
-
+
if (token.endsWith(";")) {
end--;
}
@@ -175,7 +176,7 @@ public class Utilities {
}
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcertfromfile" + e.toString());
@@ -222,7 +223,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcrlfromfile" + e.toString());
@@ -249,7 +250,7 @@ public class Utilities {
tempBuffer.append(temp);
}
-
+
return tempBuffer.toString();
} catch (Exception e) {
System.out.println("ERROR: getcafromfile" + e.toString());
@@ -264,7 +265,7 @@ public class Utilities {
*/
public static String escapeBinaryData(byte data[]) {
String result = "";
-
+
for (int i = 0; i < data.length; i++) {
String s = Integer.toHexString((int) (0xff & data[i]));
@@ -321,7 +322,7 @@ public class Utilities {
CertificateSubjectName csn1 = (CertificateSubjectName)
certinfo.get(X509CertInfo.SUBJECT);
-
+
X500Name dname = (X500Name) csn1.get(CertificateSubjectName.DN_NAME);
String pp = "";
@@ -343,7 +344,4 @@ 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 c67689e4..3b06d3d2 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/common/checkRequest.java
@@ -1,4 +1,5 @@
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
@@ -17,7 +18,6 @@ package com.netscape.pkisilent.common;
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
@@ -29,15 +29,12 @@ 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>
+ * 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;
@@ -62,27 +59,26 @@ public class checkRequest 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 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,11 +90,10 @@ 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) {
host = hs;
ports = pt;
@@ -154,11 +149,10 @@ 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;
}
@@ -166,7 +160,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));
@@ -189,9 +183,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;
}
@@ -235,8 +229,6 @@ public class checkRequest extends TestClient {
return false;
}
-
-
// Private functions
private void setElapsedTime(long dif) {
@@ -271,12 +263,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);
@@ -285,21 +277,21 @@ public class checkRequest extends TestClient {
fos.close();
}
-
+
} catch (Exception e) {
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;
}
@@ -380,8 +372,8 @@ public class checkRequest extends TestClient {
boolean st = true;
String retriveStr[] = {
- "record.base64Cert=", "record.certPrettyPrint=",
- "header.certChainBase64 = ", "header.certPrettyPrint = "};
+ "record.base64Cert=", "record.certPrettyPrint=",
+ "header.certChainBase64 = ", "header.certPrettyPrint = " };
String baseCertStr, certPrettyprintStr;
if (AUTH.equals("ra")) {
@@ -391,19 +383,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) {
@@ -475,9 +467,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:
@@ -488,7 +480,7 @@ public class checkRequest extends TestClient {
System.out.println("invalid format");
}
-
+
}
stdin.close();
socket.close();
@@ -517,9 +509,9 @@ public class checkRequest extends TestClient {
if (debug) {
System.out.println(serialNumber);
}
-
+
return st;
-
+
}
private void buildquery() {
@@ -527,7 +519,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");
@@ -592,23 +584,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 {
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 078bb588..ff541b6c 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/CertSelection.java
@@ -1,4 +1,5 @@
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
@@ -21,28 +22,24 @@ import java.util.Vector;
import org.mozilla.jss.ssl.SSLClientCertificateSelectionCallback;
+public class CertSelection implements SSLClientCertificateSelectionCallback {
-public class CertSelection implements SSLClientCertificateSelectionCallback
-{
-
- // make the select() call to use this client cert
- public static String client_cert = null;
+ // 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 df95f861..67e95cf5 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
@@ -1,4 +1,5 @@
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
@@ -25,727 +26,568 @@ 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=\\\"\\']+" +
+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=\\\"\\']+" +
+ 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=\\\"\\']+" +
+ }
+
+ /**
+ * 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=\\\"\\']+" +
+ 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() + ":" +
+ 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() + ":" +
+ } 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;
- }
-
- if (! baseURL.endsWith("/"))
- {
- baseURL = baseURL + "/";
- }
- }
-
-
-
- /**
- * 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;
- }
+ } 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;
+ }
- 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;
+ baseURL = protocolHostPort + parentDirectory;
}
- 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);
- }
+ if (!baseURL.endsWith("/")) {
+ baseURL = baseURL + "/";
}
- 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;
- }
+ /**
+ * 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 (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;
+ }
- /**
- * 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;
+ 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;
+ }
- // 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);
+ }
- // 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);
+ }
+ }
+ // 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);
+ }
- // 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);
- }
- }
+ // 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;
+ if (!tokenizer.hasMoreTokens()) {
+ return tag;
+ }
- // 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);
- }
+ 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;
+ }
+ }
+ }
+ }
+ 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;
+ }
+ }
- // 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;
+ 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;
+ }
+ }
- if (! tokenizer.hasMoreTokens())
- {
- return tag;
+ 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;
+ /**
+ * 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;
}
- } catch (Exception e) {}
- break;
+ } else if (uri.startsWith("/")) {
+ url = protocolHostPort + uri;
+ } else {
+ url = baseURL + uri;
}
- }
+
+ 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 + "/";
- }
- baseURL = uri;
- } catch (Exception e) {}
- break;
- }
- }
+ /**
+ * Retrieves the URL of this HTML document.
+ *
+ * @return The URL of this HTML document.
+ */
+ public String getDocumentURL() {
+ return documentURL;
}
- 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 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("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;
+
+ /**
+ * 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;
}
- } catch (Exception e) {}
- break;
}
- }
+
+ return textData.toString();
}
- 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;
+
+ /**
+ * 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;
}
- }
}
- }
- 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;
- }
+ String[] urlArray = new String[associatedFiles.size()];
+ associatedFiles.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 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;
+ }
+ }
- 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[documentLinks.size()];
+ documentLinks.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 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[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[documentImages.size()];
+ documentImages.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;
- }
- }
+ /**
+ * 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[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;
}
-
- 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 066fb0b4..e2d6b064 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPClient.java
@@ -1,4 +1,5 @@
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
@@ -42,1367 +43,1191 @@ 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;
-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);
+ // 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;
- }
-
- 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");
+ } 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;
}
- // 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 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;
}
- 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;
+ // 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;
- // 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;
- }
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
}
- 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;
+ 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;
+ }
+ }
+ }
+
+ // 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;
+ }
+ }
+ }
+ }
+ }
+
+ // 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);
+ }
- // 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 " +
+ 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 " +
+ 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;
- }
+ return null;
+ }
- try
- {
- statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Unable to parse response header -- could " +
+ } catch (NumberFormatException nfe) {
+ System.out.println("Unable to parse response header -- could " +
"not interpret status code as an integer");
- return null;
- }
+ return null;
+ }
- String responseMessage = statusLine.substring(spacePos2+1);
- response = new HTTPResponse(statusCode, protocolVersion,
+ 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)
- {
- 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 +
+ 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 -- " +
+ 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;
- }
+ return null;
+ }
- protocolVersion = statusLine.substring(0, spacePos);
- spacePos2 = statusLine.indexOf(' ', spacePos+1);
- if (spacePos2 < 0)
- {
- System.out.println("ERROR: Unable to parse response header -- " +
+ 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;
- }
+ return null;
+ }
- try
- {
- statusCode = Integer.parseInt(statusLine.substring(spacePos+1,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("ERROR: Unable to parse response header -- " +
+ } catch (NumberFormatException nfe) {
+ System.out.println("ERROR: Unable to parse response header -- " +
"could not interpret status code as an " +
"integer");
- return null;
- }
+ return null;
+ }
- responseMessage = statusLine.substring(spacePos2+1);
- response = new HTTPResponse(statusCode, protocolVersion,
+ responseMessage = statusLine.substring(spacePos2 + 1);
+ response = new HTTPResponse(statusCode, protocolVersion,
responseMessage);
- continue;
- }
- else
- {
- System.out.println("ERROR: Unable to parse response header -- no " +
+ 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 " +
+ 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;
- }
}
- 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;
+ // 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;
}
- }
- }
- }
- 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[] 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[] buffer2 = new byte[BUFFER_SIZE];
+ while (headerEndPos < 0) {
+ int startPos = bytesRead;
+ int moreBytesRead = inputStream.read(buffer2);
- 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;
+ 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 " +
+ // 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 " +
+ 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,
+ try {
+ statusCode = Integer.parseInt(statusLine.substring(spacePos + 1,
spacePos2));
- }
- catch (NumberFormatException nfe)
- {
- System.out.println("Unable to parse response header -- could " +
+ } 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,
+ 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 " +
+ 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 " +
+ }
+
+ 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");
- }
- }
-
-
- // 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();
+ }
+ }
+ // 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,
+ 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 " +
+ } 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,
+ } else {
+ readContentDataUsingConnectionClose(response, inputStream, buffer,
dataStartPos, bytesRead);
+ }
}
+ // Finally, return the response to the caller.
+ return response;
}
- // 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,
+
+ /**
+ * 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;
- }
-
+ throws IOException {
+ if (contentLength <= 0) {
+ response.setResponseData(new byte[0]);
+ return;
+ }
- 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,
+ 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;
- }
+ System.arraycopy(dataRead, dataStartPos, contentBytes, 0, bytesToCopy);
+ startPos = bytesToCopy;
+ }
- 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 " +
+ 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;
- }
+ System.arraycopy(buffer, 0, contentBytes, startPos, bytesRead);
+ startPos += bytesRead;
+ }
+ response.setResponseData(contentBytes);
+ }
- 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,
+ /**
+ * 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>();
+ 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;
+ }
+ // 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;
+ }
+ }
- // Create a variable to hold the total number of bytes in the data.
- int totalBytes = 0;
+ // 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;
+ }
- // 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;
+ 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;
+ }
- // 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;
+ socket.close();
+ dos.close();
+
+ }
+
+ catch (Exception e) {
+ System.err.println("Exception: Unable to Send Request:" + e);
+ e.printStackTrace();
+ st = false;
}
- else if (bytesRead > 0)
- {
- ByteBuffer byteBuffer = ByteBuffer.allocate(bytesRead);
- byteBuffer.put(buffer, 0, bytesRead);
- bufferList.add(byteBuffer);
- totalBytes += bytesRead;
+
+ 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;
}
- }
- 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;
- }
+
+ 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("###############################");
- // 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 08358f35..9ade1c13 100644
--- a/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
+++ b/pki/base/silent/src/com/netscape/pkisilent/http/HTTPResponse.java
@@ -1,4 +1,5 @@
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
@@ -17,369 +18,297 @@ 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;
+ }
-public class HTTPResponse
-{
- // The set of cookie values included in this response.
- ArrayList<String> cookieValueList;
+ /**
+ * 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;
+ }
- // The names of the headers included in this response.
- ArrayList<String> headerNameList;
+ /**
+ * 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 values of the headers included in this response.
- ArrayList<String> headerValueList;
+ /**
+ * 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 actual data associated with this response.
- byte[] responseData;
+ /**
+ * 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 HTML document included in the response, if appropriate.
- HTMLDocument htmlDocument;
+ public String getHTML() {
+ String htmlString = new String(responseData);
+ return htmlString;
+ }
- // 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 String getHTMLwithoutTags() {
+ String htmlString = new String(responseData);
+ HTMLDocument htmldocument = new HTMLDocument(htmlString);
+ return htmldocument.getTextData();
}
- return null;
- }
+ 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));
- /**
- * 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();
+ // add to array
+ this.contentName.add(name.trim());
+ this.contentValue.add(value);
+ }
+
+ }
- 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;
- }
-
-
-
- /**
- * 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 String getContentValue(String headerName) {
+ for (int i = 0; i < contentName.size(); i++) {
+ if (headerName.equals(contentName.get(i))) {
+ return contentValue.get(i);
+ }
+ }
+
+ return null;
}
- else if (lowerName.equals("content-type"))
- {
- contentType = headerValue;
+
+ public ArrayList<String> getContentNames() {
+ return contentName;
+ }
+
+ public ArrayList<String> getContentValues() {
+ return contentValue;
}
- else if (lowerName.equals("set-cookie"))
- {
- cookieValueList.add(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;
+ }
}
- }
-
-
-
- /**
- * 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 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;
}
- 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 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;
}
- else
- {
- this.responseData = responseData;
+
+ /**
+ * 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;
}
- }
-
-
-
- /**
- * 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;
+ }
+
+}