From c50ad759fa3f1294c64042c9508b3db2f32dd86b Mon Sep 17 00:00:00 2001
From: "Endi S. Dewata" <edewata@redhat.com>
Date: Wed, 23 Apr 2014 11:24:08 -0400
Subject: [PATCH] Fixed TPS connector configuration.

The code that configures the TPS connectors during installation
has been modified to use the ConnectionDatabase, which is also
used by the CLI/UI after the installation.

The code has also been fixed to configure the correct properties
as defined in CS.cfg. The static properties have been removed
from CS.cfg because now they will be generated dynamically by
the ConnectionDatabase.

Due to class dependency issue, the methods for configuring the TPS
connectors have been moved from ConfigurationUtils into a new
TPSInstaller class.

The URI's in ConfigurationRequest have been converted from String
into URI to simplify validation.

Ticket #890
---
 .../certsrv/system/ConfigurationRequest.java       |  54 ++++++---
 .../certsrv/system/SystemConfigResource.java       |   4 +-
 .../cms/servlet/csadmin/ConfigurationUtils.java    |  45 --------
 .../dogtagpki/server/rest/SystemConfigService.java |  27 +----
 base/tps-tomcat/shared/conf/CS.cfg.in              |  37 +-----
 .../server/tps/config/ConfigDatabase.java          |   6 +-
 .../server/tps/config/ConnectionDatabase.java      |  99 +++++++++++++++-
 .../server/tps/installer/CAInfoPanel.java          |   5 +-
 .../server/tps/installer/DRMInfoPanel.java         |   4 +-
 .../server/tps/installer/TKSInfoPanel.java         |   5 +-
 .../server/tps/installer/TPSInstaller.java         | 124 +++++++++++++++++++++
 .../server/tps/rest/TPSInstallerService.java       |  65 +++++------
 12 files changed, 313 insertions(+), 162 deletions(-)
 create mode 100644 base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TPSInstaller.java

diff --git a/base/common/src/com/netscape/certsrv/system/ConfigurationRequest.java b/base/common/src/com/netscape/certsrv/system/ConfigurationRequest.java
index b52344e0f538f22573f3b86cddba0cbf1454e552..fc85d3d65a75ecbcd8600299b977c358b9c15a77 100644
--- a/base/common/src/com/netscape/certsrv/system/ConfigurationRequest.java
+++ b/base/common/src/com/netscape/certsrv/system/ConfigurationRequest.java
@@ -17,6 +17,8 @@
 // --- END COPYRIGHT BLOCK ---
 package com.netscape.certsrv.system;
 
+import java.net.URI;
+import java.net.URISyntaxException;
 import java.util.List;
 
 import javax.ws.rs.core.MultivaluedMap;
@@ -24,6 +26,10 @@ import javax.xml.bind.annotation.XmlAccessType;
 import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+import org.apache.commons.lang.StringUtils;
 
 /**
  * @author alee
@@ -243,13 +249,16 @@ public class ConfigurationRequest {
     protected String authdbSecureConn;
 
     @XmlElement
-    protected String caUri;
+    @XmlJavaTypeAdapter(URIAdapter.class)
+    protected URI caUri;
 
     @XmlElement
-    protected String tksUri;
+    @XmlJavaTypeAdapter(URIAdapter.class)
+    protected URI tksUri;
 
     @XmlElement
-    protected String kraUri;
+    @XmlJavaTypeAdapter(URIAdapter.class)
+    protected URI kraUri;
 
     @XmlElement(defaultValue="false")
     protected String enableServerSideKeyGen;
@@ -270,7 +279,7 @@ public class ConfigurationRequest {
         // required for JAXB
     }
 
-    public ConfigurationRequest(MultivaluedMap<String, String> form) {
+    public ConfigurationRequest(MultivaluedMap<String, String> form) throws URISyntaxException {
         pin = form.getFirst(PIN);
         token = form.getFirst(TOKEN);
         tokenPassword = form.getFirst(TOKEN_PASSWORD);
@@ -318,9 +327,16 @@ public class ConfigurationRequest {
         authdbHost = form.getFirst(AUTHDB_HOST);
         authdbPort = form.getFirst(AUTHDB_PORT);
         authdbSecureConn = form.getFirst(AUTHDB_SECURE_CONN);
-        caUri = form.getFirst(CA_URI);
-        tksUri = form.getFirst(TKS_URI);
-        kraUri = form.getFirst(KRA_URI);
+
+        String value = form.getFirst(CA_URI);
+        if (!StringUtils.isEmpty(value)) setCaUri(new URI(value));
+
+        value = form.getFirst(TKS_URI);
+        if (!StringUtils.isEmpty(value)) setTksUri(new URI(value));
+
+        value = form.getFirst(KRA_URI);
+        if (!StringUtils.isEmpty(value)) setKraUri(new URI(value));
+
         enableServerSideKeyGen = form.getFirst(ENABLE_SERVER_SIDE_KEYGEN);
         importSharedSecret = form.getFirst(IMPORT_SHARED_SECRET);
 
@@ -883,27 +899,27 @@ public class ConfigurationRequest {
         this.authdbSecureConn = authdbSecureConn;
     }
 
-    public String getCaUri() {
+    public URI getCaUri() {
         return caUri;
     }
 
-    public void setCaUri(String caUri) {
+    public void setCaUri(URI caUri) {
         this.caUri = caUri;
     }
 
-    public String getTksUri() {
+    public URI getTksUri() {
         return tksUri;
     }
 
-    public void setTksUri(String tksUri) {
+    public void setTksUri(URI tksUri) {
         this.tksUri = tksUri;
     }
 
-    public String getKraUri() {
+    public URI getKraUri() {
         return kraUri;
     }
 
-    public void setKraUri(String kraUri) {
+    public void setKraUri(URI kraUri) {
         this.kraUri = kraUri;
     }
 
@@ -1006,4 +1022,16 @@ public class ConfigurationRequest {
                ", sharedDBUserDN=" + sharedDBUserDN +
                "]";
     }
+
+    public static class URIAdapter extends XmlAdapter<String, URI> {
+
+        public String marshal(URI uri) {
+            return uri == null ? null : uri.toString();
+        }
+
+        public URI unmarshal(String uri) throws URISyntaxException {
+            return uri == null ? null : new URI(uri);
+        }
+    }
+
 }
diff --git a/base/common/src/com/netscape/certsrv/system/SystemConfigResource.java b/base/common/src/com/netscape/certsrv/system/SystemConfigResource.java
index db4f35ac3f5600a73f8a95e831d0becab993b80b..2a490805dbfb3f3a94771fa03be7865d36153d4a 100644
--- a/base/common/src/com/netscape/certsrv/system/SystemConfigResource.java
+++ b/base/common/src/com/netscape/certsrv/system/SystemConfigResource.java
@@ -17,6 +17,8 @@
 // --- END COPYRIGHT BLOCK ---
 package com.netscape.certsrv.system;
 
+import java.net.URISyntaxException;
+
 import javax.ws.rs.Consumes;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
@@ -33,7 +35,7 @@ public interface SystemConfigResource {
     @POST
     @Path("configure")
     @Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
-    public ConfigurationResponse configure(MultivaluedMap<String, String> form);
+    public ConfigurationResponse configure(MultivaluedMap<String, String> form) throws URISyntaxException;
 
     @POST
     @Path("configure")
diff --git a/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java b/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
index 51c42b7b91a559b7804e0fffdee75beffd889c72..6f37de735b1226e82e6261bfd2b03d09511998a3 100644
--- a/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
+++ b/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
@@ -3964,51 +3964,6 @@ public class ConfigurationUtils {
         return s;
     }
 
-    public static void updateCAConnInfo(URI caUri, String subsystemNick) {
-        IConfigStore cs = CMS.getConfigStore();
-
-        cs.putString("preop.cainfo.select", caUri.toString());
-        cs.putString("conn.ca1.clientNickname", subsystemNick);
-        cs.putString("conn.ca1.hostport", caUri.getHost() + ":" + caUri.getPort());
-        cs.putString("conn.ca1.hostagentport", caUri.getHost() + ":" + caUri.getPort());
-        cs.putString("conn.ca1.hostadminport", caUri.getHost() + ":" + caUri.getPort());
-    }
-
-    public static void updateKRAConnInfo(boolean enableServerSideKeyGen, URI kraUri, String subsystemNick) {
-        IConfigStore cs = CMS.getConfigStore();
-        if (enableServerSideKeyGen) {
-            cs.putString("preop.krainfo.select", kraUri.toString());
-            cs.putString("conn.drm1.clientNickname", subsystemNick);
-            cs.putString("conn.drm1.hostport", kraUri.getHost() + ":" + kraUri.getPort());
-            cs.putString("conn.tks1.serverKeygen", "true");
-            cs.putString("op.enroll.userKey.keyGen.encryption.serverKeygen.enable", "true");
-            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.serverKeygen.enable", "true");
-            cs.putString("op.enroll.soKey.keyGen.encryption.serverKeygen.enable", "true");
-            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.serverKeygen.enable", "true");
-        } else {
-            // no keygen
-            cs.putString("conn.tks1.serverKeygen", "false");
-            cs.putString("op.enroll.userKey.keyGen.encryption.serverKeygen.enable", "false");
-            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.serverKeygen.enable", "false");
-            cs.putString("op.enroll.userKey.keyGen.encryption.recovery.destroyed.scheme", "GenerateNewKey");
-            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.recovery.onHold.scheme", "GenerateNewKey");
-            cs.putString("conn.drm1.clientNickname", "");
-            cs.putString("conn.drm1.hostport", "");
-            cs.putString("op.enroll.soKey.keyGen.encryption.serverKeygen.enable", "false");
-            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.serverKeygen.enable", "false");
-            cs.putString("op.enroll.soKey.keyGen.encryption.recovery.destroyed.scheme", "GenerateNewKey");
-            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.recovery.onHold.scheme", "GenerateNewKey");
-        }
-    }
-
-    public static void updateTKSConnInfo(URI tksUri, String subsystemNick) {
-        IConfigStore cs = CMS.getConfigStore();
-
-        cs.putString("preop.tksinfo.select", tksUri.toString());
-        cs.putString("conn.tks1.clientNickname", subsystemNick);
-        cs.putString("conn.tks1.hostport", tksUri.getHost() + ":" + tksUri.getPort());
-    }
-
     public static void updateAuthdbInfo(String basedn, String host, String port, String secureConn) {
         IConfigStore cs = CMS.getConfigStore();
 
diff --git a/base/server/cms/src/org/dogtagpki/server/rest/SystemConfigService.java b/base/server/cms/src/org/dogtagpki/server/rest/SystemConfigService.java
index 902dc88f04a5a286efcb2aa00c4b4bd5131283f6..3aad2a232843e9575fb6daecd86f2f825fbbae50 100644
--- a/base/server/cms/src/org/dogtagpki/server/rest/SystemConfigService.java
+++ b/base/server/cms/src/org/dogtagpki/server/rest/SystemConfigService.java
@@ -19,7 +19,6 @@ package org.dogtagpki.server.rest;
 
 import java.math.BigInteger;
 import java.net.MalformedURLException;
-import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.security.NoSuchAlgorithmException;
@@ -114,7 +113,7 @@ public class SystemConfigService extends PKIService implements SystemConfigResou
      * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(javax.ws.rs.core.MultivaluedMap)
      */
     @Override
-    public ConfigurationResponse configure(MultivaluedMap<String, String> form) {
+    public ConfigurationResponse configure(MultivaluedMap<String, String> form) throws URISyntaxException {
         ConfigurationRequest data = new ConfigurationRequest(form);
         return configure(data);
     }
@@ -1166,36 +1165,18 @@ public class SystemConfigService extends PKIService implements SystemConfigResou
         }
 
         if (csType.equals("TPS")) {
-            if ((data.getCaUri() == null) || data.getCaUri().isEmpty()) {
+            if (data.getCaUri() == null) {
                 throw new BadRequestException("CA URI not provided");
             }
-            try {
-                @SuppressWarnings("unused")
-                URI ca_uri = new URI(data.getCaUri());
-            } catch (URISyntaxException e) {
-                throw new BadRequestException("Invalid CA URI");
-            }
 
-            if ((data.getTksUri() == null) || data.getTksUri().isEmpty()) {
+            if (data.getTksUri() == null) {
                 throw new BadRequestException("TKS URI not provided");
             }
-            try {
-                @SuppressWarnings("unused")
-                URI tks_uri = new URI(data.getTksUri());
-            } catch (URISyntaxException e) {
-                throw new BadRequestException("Invalid TKS URI");
-            }
 
             if (data.getEnableServerSideKeyGen().equalsIgnoreCase("true")) {
-                if ((data.getKraUri() == null) || data.getKraUri().isEmpty()) {
+                if (data.getKraUri() == null) {
                     throw new BadRequestException("KRA URI required if server-side key generation requested");
                 }
-                try {
-                    @SuppressWarnings("unused")
-                    URI kra_uri = new URI(data.getKraUri());
-                } catch (URISyntaxException e) {
-                    throw new BadRequestException("Invalid KRA URI");
-                }
             }
 
             if ((data.getAuthdbBaseDN()==null) || data.getAuthdbBaseDN().isEmpty()) {
diff --git a/base/tps-tomcat/shared/conf/CS.cfg.in b/base/tps-tomcat/shared/conf/CS.cfg.in
index b9b97c8a22bd85a38a018fd44004ebfd420f9661..96c42184704d661a65814cabc03814729a7a1dc5 100644
--- a/base/tps-tomcat/shared/conf/CS.cfg.in
+++ b/base/tps-tomcat/shared/conf/CS.cfg.in
@@ -1330,7 +1330,7 @@ target.Profiles.displayname=Profile
 target.Profiles.list=userKey,soKey,soCleanUserToken,soUserKey,cleanToken,soCleanSoToken,tokenKey
 target.Profiles.pattern=op\..*\.$name\..*
 target.Subsystem_Connections.displayname=Subsystem Connection
-target.Subsystem_Connections.list=ca1,kra1,tks1
+target.Subsystem_Connections.list=
 target.Subsystem_Connections.pattern=tps.connector\.$name\..*
 tokendb._000=#########################################
 tokendb._001=# tokendb.auditLog:
@@ -1483,41 +1483,6 @@ tps.cert.audit_signing.nickname=[HSM_LABEL][NICKNAME]
 tps.cert.list=sslserver,subsystem,audit_signing
 tps.cert.sslserver.certusage=SSLServer
 tps.cert.subsystem.certusage=SSLClient
-tps.connector.ca1.enable=false
-tps.connector.ca1.host=[PKI_CA_HOSTNAME]
-tps.connector.ca1.port=[PKI_CA_PORT]
-tps.connector.ca1.minHttpConns=1
-tps.connector.ca1.maxHttpConns=15
-tps.connector.ca1.nickName=[HSM_LABEL]:[NICKNAME]
-tps.connector.ca1.timeout=30
-tps.connector.ca1.uri.enrollment=/ca/ee/ca/profileSubmitSSLClient
-tps.connector.ca1.uri.renewal=/ca/ee/ca/profileSubmitSSLClient
-tps.connector.ca1.uri.revoke=/ca/ee/subsystem/ca/doRevoke
-tps.connector.ca1.uri.unrevoke=/ca/ee/subsystem/ca/doUnrevoke
-tps.connector.kra1.enable=false
-tps.connector.kra1.host=[DRM_HOST]
-tps.connector.kra1.port=[DRM_PORT]
-tps.connector.kra1.minHttpConns=1
-tps.connector.kra1.maxHttpConns=15
-tps.connector.kra1.nickName=[HSM_LABEL]:[NICKNAME]
-tps.connector.kra1.timeout=30
-tps.connector.kra1.uri.GenerateKeyPair=/kra/agent/kra/GenerateKeyPair
-tps.connector.kra1.uri.TokenKeyRecovery=/kra/agent/kra/TokenKeyRecovery
-tps.connector.tks1.enable=false
-tps.connector.tks1.host=[TKS_HOST]
-tps.connector.tks1.port=[TKS_PORT]
-tps.connector.tks1.minHttpConns=1
-tps.connector.tks1.maxHttpConns=15
-tps.connector.tks1.nickName=[HSM_LABEL]:[NICKNAME]
-tps.connector.tks1.timeout=30
-tps.connector.tks1.generateHostChallenge=true
-tps.connector.tks1.serverKeygen=[SERVER_KEYGEN]
-tps.connector.tks1.keySet=defKeySet
-tps.connector.tks1.tksSharedSymKeyName=sharedSecret
-tps.connector.tks1.uri.computeRandomData=/tks/agent/tks/computeRandomData
-tps.connector.tks1.uri.computeSessionKey=/tks/agent/tks/computeSessionKey
-tps.connector.tks1.uri.createKeySetData=/tks/agent/tks/createKeySetData
-tps.connector.tks1.uri.encryptData=/tks/agent/tks/encryptData
 tps.operations.allowedTransitions=0:0,0:4,4:0
 usrgrp._000=##
 usrgrp._001=## User/Group
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
index b55bbba28fc104749ba6f9329d261a5b10bfb403..db0fa9aa61484633d0d9e1d6358f3fa096984fe9 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConfigDatabase.java
@@ -92,13 +92,13 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         record.setID(configID);
 
         String displayName = configStore.get("target." + configID + ".displayname");
-        if (displayName == null) {
+        if (StringUtils.isEmpty(displayName)) {
             throw new ResourceNotFoundException("Configuration " + configID + " not found.");
         }
         record.setDisplayName(displayName);
 
         String pattern = configStore.get("target." + configID + ".pattern");
-        if (pattern == null) {
+        if (StringUtils.isEmpty(pattern)) {
             throw new ResourceNotFoundException("Missing pattern for " + configID + " configuration.");
         }
 
@@ -106,7 +106,7 @@ public class ConfigDatabase extends Database<ConfigRecord> {
         record.setPattern(pattern.replace("\\|",  "|"));
 
         String list = configStore.get("target." + configID + ".list");
-        if (list != null) {
+        if (!StringUtils.isEmpty(list)) {
             record.setKeys(Arrays.asList(list.split(",")));
         }
 
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConnectionDatabase.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConnectionDatabase.java
index 4e541ed87ec5abed55daf53fb33ccca37a471c45..628fc029eef031710214976d4756520efc7c0be8 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConnectionDatabase.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/config/ConnectionDatabase.java
@@ -24,7 +24,6 @@ import java.util.Map;
 
 import com.netscape.certsrv.apps.CMS;
 import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.IConfigStore;
 import com.netscape.cmscore.dbs.CSCfgDatabase;
 
 /**
@@ -34,7 +33,7 @@ import com.netscape.cmscore.dbs.CSCfgDatabase;
  */
 public class ConnectionDatabase extends CSCfgDatabase<ConnectionRecord> {
 
-    IConfigStore configStore = CMS.getConfigStore();
+    public String prefix = "tps.connector";
 
     public ConnectionDatabase() {
         super("Connection", "Subsystem_Connections");
@@ -143,4 +142,100 @@ public class ConnectionDatabase extends CSCfgDatabase<ConnectionRecord> {
 
         configDatabase.commit();
     }
+
+    public String getNextID(String type) throws Exception {
+
+        ConfigDatabase configDatabase = new ConfigDatabase();
+        ConfigRecord configRecord = configDatabase.getRecord(substoreName);
+        Collection<String> keys = configRecord.getKeys();
+
+        String id;
+        int n = 1;
+
+        while (true) {
+            id = type + n;
+
+            if (keys.contains(id)) {
+                // ID is already used, find the next one.
+                n++;
+
+            } else {
+                // ID is available, use this one.
+                break;
+            }
+        }
+
+        return id;
+    }
+
+    public void addCAConnector(String hostname, Integer port, String nickname) throws Exception {
+
+        String id  = getNextID("ca");
+
+        ConnectionRecord record = new ConnectionRecord();
+        record.setID(id);
+        record.setStatus("Enabled");
+
+        record.setProperty(prefix + "." + id + ".enable", "true");
+        record.setProperty(prefix + "." + id + ".host", hostname);
+        record.setProperty(prefix + "." + id + ".port", port.toString());
+        record.setProperty(prefix + "." + id + ".minHttpConns", "1");
+        record.setProperty(prefix + "." + id + ".maxHttpConns", "15");
+        record.setProperty(prefix + "." + id + ".nickName", nickname);
+        record.setProperty(prefix + "." + id + ".timeout", "30");
+        record.setProperty(prefix + "." + id + ".uri.enrollment", "/ca/ee/ca/profileSubmitSSLClient");
+        record.setProperty(prefix + "." + id + ".uri.renewal", "/ca/ee/ca/profileSubmitSSLClient");
+        record.setProperty(prefix + "." + id + ".uri.revoke", "/ca/ee/subsystem/ca/doRevoke");
+        record.setProperty(prefix + "." + id + ".uri.unrevoke", "/ca/ee/subsystem/ca/doUnrevoke");
+
+        addRecord(id, record);
+    }
+
+    public void addKRAConnector(String hostname, Integer port, String nickname) throws Exception {
+
+        String id  = getNextID("kra");
+
+        ConnectionRecord record = new ConnectionRecord();
+        record.setID(id);
+        record.setStatus("Enabled");
+
+        record.setProperty(prefix + "." + id + ".enable", "true");
+        record.setProperty(prefix + "." + id + ".host", hostname);
+        record.setProperty(prefix + "." + id + ".port", port.toString());
+        record.setProperty(prefix + "." + id + ".minHttpConns", "1");
+        record.setProperty(prefix + "." + id + ".maxHttpConns", "15");
+        record.setProperty(prefix + "." + id + ".nickName", nickname);
+        record.setProperty(prefix + "." + id + ".timeout", "30");
+        record.setProperty(prefix + "." + id + ".uri.GenerateKeyPair", "/kra/agent/kra/GenerateKeyPair");
+        record.setProperty(prefix + "." + id + ".uri.TokenKeyRecovery", "/kra/agent/kra/TokenKeyRecovery");
+
+        addRecord(id, record);
+    }
+
+    public void addTKSConnector(String hostname, Integer port, String nickname, Boolean keygen) throws Exception {
+
+        String id  = getNextID("tks");
+
+        ConnectionRecord record = new ConnectionRecord();
+        record.setID(id);
+        record.setStatus("Enabled");
+
+        record.setProperty(prefix + "." + id + ".enable", "true");
+        record.setProperty(prefix + "." + id + ".host", hostname);
+        record.setProperty(prefix + "." + id + ".port", port.toString());
+        record.setProperty(prefix + "." + id + ".minHttpConns", "1");
+        record.setProperty(prefix + "." + id + ".maxHttpConns", "15");
+        record.setProperty(prefix + "." + id + ".nickName", nickname);
+        record.setProperty(prefix + "." + id + ".timeout", "30");
+        record.setProperty(prefix + "." + id + ".generateHostChallenge", "true");
+        record.setProperty(prefix + "." + id + ".serverKeygen", keygen.toString());
+        record.setProperty(prefix + "." + id + ".keySet", "defKeySet");
+        record.setProperty(prefix + "." + id + ".tksSharedSymKeyName", "sharedSecret");
+        record.setProperty(prefix + "." + id + ".uri.computeRandomData", "/tks/agent/tks/computeRandomData");
+        record.setProperty(prefix + "." + id + ".uri.computeSessionKey", "/tks/agent/tks/computeSessionKey");
+        record.setProperty(prefix + "." + id + ".uri.createKeySetData", "/tks/agent/tks/createKeySetData");
+        record.setProperty(prefix + "." + id + ".uri.encryptData", "/tks/agent/tks/encryptData");
+
+        addRecord(id, record);
+    }
 }
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/CAInfoPanel.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/CAInfoPanel.java
index a0dbdaff7e1d98723dc87b9cb29c747503162b63..4c5371f200f37d4b547f9663983a4af803830628 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/CAInfoPanel.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/CAInfoPanel.java
@@ -137,7 +137,10 @@ public class CAInfoPanel extends WizardPanelBase {
         } catch (URISyntaxException e) {
             throw new IOException("Invalid URI " + parsedURI);
         }
-        ConfigurationUtils.updateCAConnInfo(caUri, subsystemNick);
+
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureCAConnector(caUri, subsystemNick);
 
         String host = caUri.getHost();
         int port = caUri.getPort();
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/DRMInfoPanel.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/DRMInfoPanel.java
index 467f8623cc9d3af5d7c7c7e9f3a878eb316b5292..2237f9e5342d10127ffc7521af38c37746bdc409 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/DRMInfoPanel.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/DRMInfoPanel.java
@@ -137,7 +137,9 @@ public class DRMInfoPanel extends WizardPanelBase {
         String choice = HttpInput.getString(request, "choice");
         boolean keyGen = choice.equalsIgnoreCase("keygen");
 
-        ConfigurationUtils.updateKRAConnInfo(keyGen, kraUri, subsystemNick);
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureKRAConnector(keyGen, kraUri, subsystemNick);
 
         context.put("updateStatus", "success");
     }
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TKSInfoPanel.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TKSInfoPanel.java
index 2bfefbf03e78dc430f73b2677d709bdc15be0fa9..0c0cf62a7aa3acc7bfe5ad9f9047b8497fcf2139 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TKSInfoPanel.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TKSInfoPanel.java
@@ -135,7 +135,10 @@ public class TKSInfoPanel extends WizardPanelBase {
             throw new IOException("Invalid URI " + parsedURI);
         }
 
-        ConfigurationUtils.updateTKSConnInfo(tksUri, subsystemNick);
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureTKSConnector(tksUri, subsystemNick);
+
         context.put("updateStatus", "success");
     }
 
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TPSInstaller.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TPSInstaller.java
new file mode 100644
index 0000000000000000000000000000000000000000..9d9226b46ed2a14b8b39f795481ab1718a94d5de
--- /dev/null
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/installer/TPSInstaller.java
@@ -0,0 +1,124 @@
+// --- 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
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2014 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package org.dogtagpki.server.tps.installer;
+
+import java.net.URI;
+
+import org.dogtagpki.server.tps.TPSSubsystem;
+import org.dogtagpki.server.tps.config.ConnectionDatabase;
+import org.dogtagpki.server.tps.config.ConnectionRecord;
+
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.base.IConfigStore;
+import com.netscape.certsrv.base.PKIException;
+
+/**
+ * Utility class for TPS installation to be used both by the RESTful installer
+ * and the UI Panels.
+ *
+ * @author alee
+ *
+ */
+
+public class TPSInstaller {
+
+    public TPSInstaller() {
+    }
+
+    public void configureCAConnector(URI uri, String nickname) {
+
+        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+        ConnectionDatabase database = subsystem.getConnectionDatabase();
+        IConfigStore cs = CMS.getConfigStore();
+
+        // TODO: see if this is only needed by wizard-based installation
+        cs.putString("preop.cainfo.select", uri.toString());
+
+        try {
+            database.addCAConnector(uri.getHost(), uri.getPort(), nickname);
+
+        } catch (Exception e) {
+            throw new PKIException("Unable to create CA connector", e);
+        }
+    }
+
+    public void configureTKSConnector(URI uri, String nickname) {
+
+        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+        ConnectionDatabase database = subsystem.getConnectionDatabase();
+        IConfigStore cs = CMS.getConfigStore();
+
+        // TODO: see if this is only needed by wizard-based installation
+        cs.putString("preop.tksinfo.select", uri.toString());
+
+        try {
+            database.addTKSConnector(uri.getHost(), uri.getPort(), nickname, false);
+
+        } catch (Exception e) {
+            throw new PKIException("Unable to create TKS connector", e);
+        }
+    }
+
+    public void configureKRAConnector(Boolean keygen, URI uri, String nickname) {
+
+        TPSSubsystem subsystem = (TPSSubsystem)CMS.getSubsystem(TPSSubsystem.ID);
+        ConnectionDatabase database = subsystem.getConnectionDatabase();
+        IConfigStore cs = CMS.getConfigStore();
+
+        if (keygen) {
+            // TODO: see if this is only needed by wizard-based installation
+            cs.putString("preop.krainfo.select", uri.toString());
+
+            // TODO: see if there are other profiles need to be configured
+            cs.putString("op.enroll.userKey.keyGen.encryption.serverKeygen.enable", "true");
+            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.serverKeygen.enable", "true");
+            cs.putString("op.enroll.soKey.keyGen.encryption.serverKeygen.enable", "true");
+            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.serverKeygen.enable", "true");
+
+            try {
+                database.addKRAConnector(uri.getHost(), uri.getPort(), nickname);
+
+            } catch (Exception e) {
+                throw new PKIException("Unable to create KRA connector", e);
+            }
+
+        } else { // no keygen
+            // TODO: see if there are other profiles need to be configured
+            cs.putString("op.enroll.userKey.keyGen.encryption.serverKeygen.enable", "false");
+            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.serverKeygen.enable", "false");
+            cs.putString("op.enroll.userKey.keyGen.encryption.recovery.destroyed.scheme", "GenerateNewKey");
+            cs.putString("op.enroll.userKeyTemporary.keyGen.encryption.recovery.onHold.scheme", "GenerateNewKey");
+            cs.putString("op.enroll.soKey.keyGen.encryption.serverKeygen.enable", "false");
+            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.serverKeygen.enable", "false");
+            cs.putString("op.enroll.soKey.keyGen.encryption.recovery.destroyed.scheme", "GenerateNewKey");
+            cs.putString("op.enroll.soKeyTemporary.keyGen.encryption.recovery.onHold.scheme", "GenerateNewKey");
+        }
+
+        try {
+            String id = "tks1"; // there is only one default TKS connector
+
+            // update keygen in TKS connector
+            ConnectionRecord record = database.getRecord(id);
+            record.setProperty(database.prefix + "." + id + ".serverKeygen", keygen.toString());
+            database.updateRecord(id, record);
+
+        } catch (Exception e) {
+            throw new PKIException("Unable to update TKS connector", e);
+        }
+    }
+}
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java
index b4dca6c7c6f98188f7d30beade248debf78a9d8a..9c4943b9f50019e629ecfacb87862ef997071f91 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/rest/TPSInstallerService.java
@@ -22,6 +22,7 @@ import java.net.URISyntaxException;
 import java.util.Collection;
 
 import org.dogtagpki.server.rest.SystemConfigService;
+import org.dogtagpki.server.tps.installer.TPSInstaller;
 
 import com.netscape.certsrv.apps.CMS;
 import com.netscape.certsrv.base.BadRequestException;
@@ -37,6 +38,7 @@ import com.netscape.cms.servlet.csadmin.ConfigurationUtils;
  */
 public class TPSInstallerService extends SystemConfigService  {
 
+
     public TPSInstallerService() throws EBaseException {
     }
 
@@ -47,26 +49,26 @@ public class TPSInstallerService extends SystemConfigService  {
         super.configureSubsystem(request, certList, token, domainXML);
 
         // get subsystem certificate nickname
-        String subsystemNick = null;
-        for (SystemCertData cdata : request.getSystemCerts()) {
-            if (cdata.getTag().equals("subsystem")) {
-                subsystemNick = cdata.getNickname();
+        String nickname = null;
+        for (SystemCertData cert : request.getSystemCerts()) {
+            if (cert.getTag().equals("subsystem")) {
+                nickname = cert.getNickname();
                 break;
             }
         }
 
-        if (subsystemNick == null || subsystemNick.isEmpty()) {
+        if (nickname == null || nickname.isEmpty()) {
             throw new BadRequestException("No nickname provided for subsystem certificate");
         }
 
         // CA Info Panel
-        configureTPStoCAConnector(request, subsystemNick);
+        configureCAConnector(request, nickname);
 
         // TKS Info Panel
-        configureTPStoTKSConnector(request, subsystemNick);
+        configureTKSConnector(request, nickname);
 
         //DRM Info Panel
-        configureTPStoKRAConnector(request, subsystemNick);
+        configureKRAConnector(request, nickname);
 
         //AuthDBPanel
         ConfigurationUtils.updateAuthdbInfo(request.getAuthdbBaseDN(),
@@ -74,36 +76,27 @@ public class TPSInstallerService extends SystemConfigService  {
                 request.getAuthdbSecureConn());
     }
 
-    public void configureTPStoCAConnector(ConfigurationRequest data, String subsystemNick) {
-        URI caUri = null;
-        try {
-            caUri = new URI(data.getCaUri());
-        } catch (URISyntaxException e) {
-            throw new BadRequestException("Invalid caURI " + caUri);
-        }
-        ConfigurationUtils.updateCAConnInfo(caUri, subsystemNick);
+    public void configureCAConnector(ConfigurationRequest request, String nickname) {
+
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureCAConnector(request.getCaUri(), nickname);
     }
 
-    public void configureTPStoTKSConnector(ConfigurationRequest data, String subsystemNick) {
-        URI tksUri = null;
-        try {
-            tksUri = new URI(data.getTksUri());
-        } catch (URISyntaxException e) {
-            throw new BadRequestException("Invalid tksURI " + tksUri);
-        }
+    public void configureTKSConnector(ConfigurationRequest request, String nickname) {
 
-        ConfigurationUtils.updateTKSConnInfo(tksUri, subsystemNick);
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureTKSConnector(request.getTksUri(), nickname);
     }
 
-    public void configureTPStoKRAConnector(ConfigurationRequest data, String subsystemNick) {
-        URI kraUri = null;
-        try {
-            kraUri = new URI(data.getCaUri());
-        } catch (URISyntaxException e) {
-            throw new BadRequestException("Invalid kraURI " + kraUri);
-        }
-        boolean keyGen = data.getEnableServerSideKeyGen().equalsIgnoreCase("true");
-        ConfigurationUtils.updateKRAConnInfo(keyGen, kraUri, subsystemNick);
+    public void configureKRAConnector(ConfigurationRequest request, String nickname) {
+
+        boolean keygen = request.getEnableServerSideKeyGen().equalsIgnoreCase("true");
+
+        // TODO: get installer from session
+        TPSInstaller installer = new TPSInstaller();
+        installer.configureKRAConnector(keygen, request.getKraUri(), nickname);
     }
 
     @Override
@@ -129,15 +122,15 @@ public class TPSInstallerService extends SystemConfigService  {
             URI secdomainURI = new URI(request.getSecurityDomainUri());
 
             // register TPS with CA
-            URI caURI = new URI(request.getCaUri());
+            URI caURI = request.getCaUri();
             ConfigurationUtils.registerUser(secdomainURI, caURI, "ca");
 
             // register TPS with TKS
-            URI tksURI = new URI(request.getTksUri());
+            URI tksURI = request.getTksUri();
             ConfigurationUtils.registerUser(secdomainURI, tksURI, "tks");
 
             if (request.getEnableServerSideKeyGen().equalsIgnoreCase("true")) {
-                URI kraURI = new URI(request.getKraUri());
+                URI kraURI = request.getKraUri();
                 ConfigurationUtils.registerUser(secdomainURI, kraURI, "kra");
                 String transportCert = ConfigurationUtils.getTransportCert(secdomainURI, kraURI);
                 ConfigurationUtils.exportTransportCert(secdomainURI, tksURI, transportCert);
-- 
1.8.4.2

