From 9a8d40eda19e7fb60c513e653f04c3a2967d72ec Mon Sep 17 00:00:00 2001
From: Jack Magne <jmagne@dhcp-16-213.sjc.redhat.com>
Date: Tue, 18 Mar 2014 18:34:08 -0700
Subject: [PATCH] Further work on TPS Processor, format operation.

Further review changes, including:

1. Error handling.
2. Get rid of TPSFormatProcessor class, for now.
3. More error handling.
4. Moving around some constants.
---
 .../src/org/dogtagpki/tps/apdu/APDUResponse.java   |  31 ++
 .../src/org/dogtagpki/tps/msg/TPSMessage.java      |  44 +--
 .../src/org/dogtagpki/server/tps/TPSSession.java   |  65 ++--
 .../org/dogtagpki/server/tps/engine/TPSEngine.java |  27 +-
 .../server/tps/processor/TPSFormatProcessor.java   |  46 ---
 .../server/tps/processor/TPSProcessor.java         | 412 +++++++++------------
 6 files changed, 260 insertions(+), 365 deletions(-)
 delete mode 100644 base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSFormatProcessor.java

diff --git a/base/common/src/org/dogtagpki/tps/apdu/APDUResponse.java b/base/common/src/org/dogtagpki/tps/apdu/APDUResponse.java
index d0fc64b..ef25cd2 100644
--- a/base/common/src/org/dogtagpki/tps/apdu/APDUResponse.java
+++ b/base/common/src/org/dogtagpki/tps/apdu/APDUResponse.java
@@ -22,6 +22,9 @@
 package org.dogtagpki.tps.apdu;
 
 import org.dogtagpki.tps.main.TPSBuffer;
+import org.dogtagpki.tps.main.Util;
+
+import com.netscape.certsrv.apps.CMS;
 
 public class APDUResponse extends APDU {
 
@@ -65,6 +68,34 @@ public class APDUResponse extends APDU {
 
     }
 
+    //Not every non 0x90 0x00 is considered fatal, return result
+    public boolean checkResult() {
+        boolean result = false;
+
+        byte sw1 = getSW1();
+        byte sw2 = getSW2();
+
+        int int1 = sw1 & 0xff;
+        int int2 = sw2 & 0xff;
+
+        CMS.debug("APDUResponse.checkResult : sw1: " + "0x" + Util.intToHex(int1) + " sw2: " + "0x"
+                + Util.intToHex(int2));
+
+        if (sw1 == (byte) 0x90 && sw2 == 0x0)
+            result = true;
+
+        return result;
+    }
+
+    //Get the two byte apdu return code
+    byte[] getResultBytes() {
+        byte[] result = new byte[2];
+
+        result[0] = getSW1();
+        result[1] = getSW2();
+        return result;
+    }
+
     public static void main(String args[]) {
 
         APDUResponse resp = new APDUResponse();
diff --git a/base/common/src/org/dogtagpki/tps/msg/TPSMessage.java b/base/common/src/org/dogtagpki/tps/msg/TPSMessage.java
index f6d238b..036c44c 100644
--- a/base/common/src/org/dogtagpki/tps/msg/TPSMessage.java
+++ b/base/common/src/org/dogtagpki/tps/msg/TPSMessage.java
@@ -17,6 +17,7 @@
 // --- END COPYRIGHT BLOCK ---
 package org.dogtagpki.tps.msg;
 
+import java.io.IOException;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
@@ -401,7 +402,7 @@ public class TPSMessage {
         return result;
     }
 
-    private TPSMessage createMessage() {
+    private TPSMessage createMessage() throws IOException {
 
         TPSMessage result = null;
 
@@ -416,13 +417,7 @@ public class TPSMessage {
         String decoded = null;
         Map<String, String> extsMap = null;
         if (extensions != null) {
-            try {
-                decoded = Util.uriDecode(extensions);
-            } catch (Exception e) {
-                CMS.debug("TPSMessage.createMessage: Util.URIDecode failed: " + e);
-                return null;
-            }
-
+            decoded = Util.uriDecode(extensions);
             System.out.println("decoded extensions : " + decoded);
 
             extsMap = decodeToMap(decoded);
@@ -431,15 +426,11 @@ public class TPSMessage {
         int msg_type_int = 0;
         int op_type_int = 0;
 
-        try {
-            if (msg_type != null) {
-                msg_type_int = Integer.parseInt(msg_type);
-            }
-            if (op_type != null) {
-                op_type_int = Integer.parseInt(op_type);
-            }
-        } catch (NumberFormatException e) {
-            CMS.debug("TPSMessage.createMessage: Error obtaining msg_type or op_type from incoming message.");
+        if (msg_type != null) {
+            msg_type_int = Integer.parseInt(msg_type);
+        }
+        if (op_type != null) {
+            op_type_int = Integer.parseInt(op_type);
         }
 
         MsgType val = intToMsgType(msg_type_int);
@@ -481,29 +472,22 @@ public class TPSMessage {
         case MSG_TOKEN_PDU_RESPONSE:
             result = new TokenPDUResponse(encode());
             break;
-        case MSG_UNDEFINED:
-            return result;
         default:
-            return result;
-
+            //Something was garbled with the message coming in
+            throw new IOException("TPSMessage.createMessage: Can't create incoming TPS message!");
         }
 
         return result;
 
     }
 
-    public static TPSMessage createMessage(String message) {
+    public static TPSMessage createMessage(String message) throws IOException {
 
         CMS.debug("TPSMessage.createMessage: message: " + message);
 
-        TPSMessage new_msg = null;
-        TPSMessage returnMsg = null;
-
-        new_msg = new TPSMessage(message);
-
-        returnMsg = new_msg.createMessage();
+        TPSMessage new_msg = new TPSMessage(message);
 
-        return returnMsg;
+        return new_msg.createMessage();
     }
 
     public MsgType getType() {
@@ -512,7 +496,7 @@ public class TPSMessage {
         return intToMsgType(res);
     }
 
-    public static void main(String[] args) {
+    public static void main(String[] args) throws IOException {
         String encoded = "s=204&msg_type=2&operation=5&extensions=tokenType%3DuserKey%26clientVersion%3DESC+1%2E0%2E1%26tokenATR%3D3BFF1400FF8131FE458025A00000005657534336353003003B%26statusUpdate%3Dtrue%26extendedLoginRequest%3Dtrue%26";
         BeginOp testMessage = (BeginOp) TPSMessage.createMessage(encoded);
         System.out.println("Encoded msg: " + testMessage.encode());
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSession.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSession.java
index 79ca435..85c5682 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSession.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/TPSSession.java
@@ -19,7 +19,7 @@ package org.dogtagpki.server.tps;
 
 import java.io.IOException;
 
-import org.dogtagpki.server.tps.processor.TPSFormatProcessor;
+import org.dogtagpki.server.tps.processor.TPSProcessor;
 import org.dogtagpki.tps.TPSConnection;
 import org.dogtagpki.tps.main.TPSException;
 import org.dogtagpki.tps.msg.BeginOp;
@@ -34,6 +34,10 @@ public class TPSSession {
 
     public TPSSession(TPSConnection conn) {
 
+        if (conn == null) {
+            throw new NullPointerException("TPSSession incoming connection is null!");
+        }
+
         CMS.debug("TPSSession constructor conn: " + conn);
         connection = conn;
     }
@@ -45,20 +49,16 @@ public class TPSSession {
     public TPSMessage read() throws IOException {
         TPSMessage message = null;
 
-        if (connection != null) {
-            CMS.debug("TPSSession.process() about to call read on connection : " + connection);
+        CMS.debug("TPSSession.process() about to call read on connection : " + connection);
 
-            try {
-                message = connection.read();
-                CMS.debug("TPSSession.process() created message " + message);
+        try {
+            message = connection.read();
+            CMS.debug("TPSSession.process() created message " + message);
 
-            } catch (Exception e) {
-                //Catch here so we can log
-                CMS.debug("Exception reading from the client: " + e.toString());
-                throw new IOException(e.toString());
-            }
-        } else {
-            throw new IOException("No connection available in TPSSession instance!");
+        } catch (IOException e) {
+            //Catch here so we can log
+            CMS.debug("TPSSession.process: Exception reading from the client: " + e.toString());
+            throw new IOException(e);
         }
 
         return message;
@@ -66,19 +66,14 @@ public class TPSSession {
 
     public void write(TPSMessage msg) throws IOException {
 
-        if (connection != null) {
-
-            try {
-                connection.write(msg);
-            } catch (Exception e) {
-                //Catch here so we can log
-                CMS.debug("Exception reading from the client: " + e.toString());
-                throw new IOException(e.toString());
-            }
-
-        } else {
-            throw new IOException("No conneciton available in TPSSession instance!");
+        try {
+            connection.write(msg);
+        } catch (Exception e) {
+            //Catch here so we can log
+            CMS.debug("Exception writing to client: " + e.toString());
+            throw new IOException(e);
         }
+
     }
 
     public void process() throws IOException {
@@ -87,26 +82,22 @@ public class TPSSession {
 
         TPSMessage firstMsg = read();
 
-        if (firstMsg == null) {
-            throw new IOException("Can't create first TPSMessage!");
-        }
-
         TPSMessage.MsgType msg_type = firstMsg.getType();
         TPSMessage.OpType op_type = firstMsg.getOpType();
 
         if (msg_type != TPSMessage.MsgType.MSG_BEGIN_OP) {
-            throw new IOException("Wong first message type read in TPSSession.process!");
+            throw new IOException("Wrong first message type read in TPSSession.process!");
         }
 
-        int result = EndOp.RESULT_ERROR;
+        int result = EndOp.RESULT_GOOD;
         try {
 
             switch (op_type) {
             case OP_FORMAT:
 
-                TPSFormatProcessor processor = new TPSFormatProcessor(this);
+                TPSProcessor processor = new TPSProcessor(this);
                 BeginOp beginOp = (BeginOp) firstMsg;
-                status = processor.process(beginOp);
+                processor.process(beginOp);
 
             case OP_ENROLL:
                 break;
@@ -126,19 +117,15 @@ public class TPSSession {
             //Get the status from the exception and return it to the client.
             CMS.debug("TPSSession.process: Message processing failed: " + e);
             status = e.getStatus();
+            result = EndOp.RESULT_ERROR;
         } catch (IOException e) {
             CMS.debug("TPSSession.process: IO error happened during processing: " + e);
-           // We get here we are done.
+            // We get here we are done.
             throw new IOException(e);
 
         }
 
-        if (status == EndOp.TPSStatus.STATUS_NO_ERROR) {
-            result = EndOp.RESULT_GOOD;
-        }
-
         EndOp endOp = new EndOp(firstMsg.getOpType(), result, status);
-
         write(endOp);
 
         CMS.debug("TPSSession.process: leaving: result: " + result + " status: " + status);
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/engine/TPSEngine.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/engine/TPSEngine.java
index 7d60bcd..548e0ca 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/engine/TPSEngine.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/engine/TPSEngine.java
@@ -19,13 +19,6 @@ package org.dogtagpki.server.tps.engine;
 
 public class TPSEngine {
 
-    public static final String TKS_RESPONSE_STATUS = "status";
-    public static final String TKS_RESPONSE_SessionKey = "sessionKey";
-    public static final String TKS_RESPONSE_EncSessionKey = "encSessionKey";
-    public static final String TKS_RESPONSE_KEK_DesKey = "kek_wrapped_desKey";
-    public static final String TKS_RESPONSE_DRM_Trans_DesKey = "drm_trans_wrapped_desKey";
-    public static final String TKS_RESPONSE_HostCryptogram = "hostCryptogram";
-
     public static final String CFG_DEBUG_ENABLE = "logging.debug.enable";
     public static final String CFG_DEBUG_FILENAME = "logging.debug.filename";
     public static final String CFG_DEBUG_LEVEL = "logging.debug.level";
@@ -50,9 +43,9 @@ public class TPSEngine {
     public static final String CFG_APPLET_NETKEY_OLD_FILE_AID = "applet.aid.netkey_old_file";
     public static final String CFG_APPLET_SO_PIN = "applet.so_pin";
     public static final String CFG_APPLET_DELETE_NETKEY_OLD = "applet.delete_old";
-    public static final String CFG_AUDIT_SELECTED_EVENTS="logging.audit.selected.events";
-    public static final String CFG_AUDIT_NONSELECTABLE_EVENTS="logging.audit.nonselectable.events";
-    public static final String CFG_AUDIT_SELECTABLE_EVENTS="logging.audit.selectable.events";
+    public static final String CFG_AUDIT_SELECTED_EVENTS = "logging.audit.selected.events";
+    public static final String CFG_AUDIT_NONSELECTABLE_EVENTS = "logging.audit.nonselectable.events";
+    public static final String CFG_AUDIT_SELECTABLE_EVENTS = "logging.audit.selectable.events";
     public static final String CFG_AUDIT_BUFFER_SIZE = "logging.audit.buffer.size";
     public static final String CFG_AUDIT_FLUSH_INTERVAL = "logging.audit.flush.interval";
     public static final String CFG_AUDIT_FILE_TYPE = "logging.audit.file.type";
@@ -68,12 +61,12 @@ public class TPSEngine {
 
     public static final String CFG_PRINTBUF_FULL = "tps.printBufFull";
     public static final String CFG_RECV_BUF_SIZE = "tps.recvBufSize";
-    public static final String CFG_AUTHS_ENABLE="auth.enable";
-    public static final String CFG_PROFILE_MAPPING_ORDER="mapping.order";
-    public static final String CFG_ALLOW_UNKNOWN_TOKEN="allowUnkonwnToken";
-    public static final String CFG_ALLOW_NO_APPLET="update.applet.emptyToken.enable";
-    public static final String CFG_APPLET_UPDATE_REQUIRED_VERSION="update.applet.requiredVersion";
-    public static final String CFG_APPLET_DIRECTORY="update.applet.directory";
+    public static final String CFG_AUTHS_ENABLE = "auth.enable";
+    public static final String CFG_PROFILE_MAPPING_ORDER = "mapping.order";
+    public static final String CFG_ALLOW_UNKNOWN_TOKEN = "allowUnkonwnToken";
+    public static final String CFG_ALLOW_NO_APPLET = "update.applet.emptyToken.enable";
+    public static final String CFG_APPLET_UPDATE_REQUIRED_VERSION = "update.applet.requiredVersion";
+    public static final String CFG_APPLET_DIRECTORY = "update.applet.directory";
 
     /* default values */
     public static final String CFG_DEF_CARDMGR_INSTANCE_AID = "A0000000030000";
@@ -82,6 +75,7 @@ public class TPSEngine {
     public static final String CFG_DEF_NETKEY_OLD_INSTANCE_AID = "A00000000101";
     public static final String CFG_DEF_NETKEY_OLD_FILE_AID = "A000000001";
     public static final String CFG_DEF_APPLET_SO_PIN = "000000000000";
+    public static final String CFG_ENABLED="Enabled";
 
     /* External reg values */
 
@@ -91,7 +85,6 @@ public class TPSEngine {
 
     public static final String OP_FORMAT_PREFIX = "op.format";
 
-
     public void init() {
         //ToDo
     }
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSFormatProcessor.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSFormatProcessor.java
deleted file mode 100644
index 8a75f73..0000000
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSFormatProcessor.java
+++ /dev/null
@@ -1,46 +0,0 @@
-// --- 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) 2013 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-package org.dogtagpki.server.tps.processor;
-
-import java.io.IOException;
-
-import org.dogtagpki.server.tps.TPSSession;
-import org.dogtagpki.tps.main.TPSException;
-import org.dogtagpki.tps.msg.BeginOp;
-import org.dogtagpki.tps.msg.EndOp.TPSStatus;
-
-import com.netscape.certsrv.apps.CMS;
-
-public class TPSFormatProcessor extends TPSProcessor {
-
-    public TPSFormatProcessor(TPSSession session) {
-        super(session);
-    }
-
-
-    public TPSStatus process(BeginOp beginMsg) throws TPSException, IOException {
-        CMS.debug("In TPS_Format_Processor.Process.");
-        return super.format(beginMsg);
-    }
-
-    public static void main(String[] args) {
-        // TODO Auto-generated method stub
-
-    }
-
-}
diff --git a/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSProcessor.java b/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSProcessor.java
index b6340af..6f84a30 100644
--- a/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSProcessor.java
+++ b/base/tps-tomcat/src/org/dogtagpki/server/tps/processor/TPSProcessor.java
@@ -32,7 +32,6 @@ import org.dogtagpki.tps.apdu.GetVersion;
 import org.dogtagpki.tps.apdu.Select;
 import org.dogtagpki.tps.main.TPSBuffer;
 import org.dogtagpki.tps.main.TPSException;
-import org.dogtagpki.tps.main.Util;
 import org.dogtagpki.tps.msg.BeginOp;
 import org.dogtagpki.tps.msg.EndOp.TPSStatus;
 import org.dogtagpki.tps.msg.TokenPDURequest;
@@ -43,7 +42,7 @@ import com.netscape.certsrv.base.EBaseException;
 import com.netscape.certsrv.base.EPropertyNotFound;
 import com.netscape.certsrv.base.IConfigStore;
 
-public abstract class TPSProcessor {
+public class TPSProcessor {
 
     public static final int RESULT_NO_ERROR = 0;
     public static final int RESULT_ERROR = -1;
@@ -55,12 +54,16 @@ public abstract class TPSProcessor {
     private boolean isExternalReg;
 
     private TPSSession session;
+    private String selectedTokenType;
 
     public TPSProcessor(TPSSession session) {
-        this.session = session;
+        setSession(session);
     }
 
     protected void setSession(TPSSession session) {
+        if (session == null) {
+            throw new NullPointerException("TPS session is null");
+        }
         this.session = session;
     }
 
@@ -68,23 +71,36 @@ public abstract class TPSProcessor {
         return session;
     }
 
-    protected TPSBuffer extractTokenNSM(TPSBuffer cplc_data) {
+    protected void setSelectedTokenType(String theTokenType) {
+
+        if (theTokenType == null) {
+            throw new NullPointerException("TPSProcessor.setSelectedTokenType: Attempt to set invalid null token type!");
+        }
+        selectedTokenType = theTokenType;
+    }
+
+    protected String getSelectedTokenType() {
+        return selectedTokenType;
+    }
+
+    protected TPSBuffer extractTokenMSN(TPSBuffer cplc_data) throws TPSException {
+        //Just make sure no one is inputing bogus cplc_data
         if (cplc_data == null || cplc_data.size() < CPLC_DATA_SIZE) {
-            CMS.debug("TPS_Processor.extractTokenMSN: cplc_data: invalid length.");
-            return null;
+            throw new TPSException("TPSProcessor.extractTokenMSN: Can't extract token msn from cplc data!",
+                    TPSStatus.STATUS_ERROR_SECURE_CHANNEL);
         }
 
         TPSBuffer token_msn = cplc_data.substr(CPLC_MSN_INDEX, CPLC_MSN_SIZE);
-
         return token_msn;
 
     }
 
-    protected TPSBuffer extractTokenCUID(TPSBuffer cplc_data) {
-
-        if (cplc_data == null || cplc_data.size() < 47) {
+    protected TPSBuffer extractTokenCUID(TPSBuffer cplc_data) throws TPSException {
+        //Just make sure no one is inputing bogus cplc_data
+        if (cplc_data == null || cplc_data.size() < CPLC_DATA_SIZE) {
             CMS.debug("TPS_Processor.extractTokenCUID: cplc_data: invalid length.");
-            return null;
+            throw new TPSException("TPSProcessor.extractTokenCUID: Can't extract cuid from cplc data!",
+                    TPSStatus.STATUS_ERROR_SECURE_CHANNEL);
         }
 
         TPSBuffer token1 = cplc_data.substr(3, 4);
@@ -101,11 +117,6 @@ public abstract class TPSProcessor {
 
     }
 
-    protected int selectCardManager(String prefix, String tokenType) {
-        //ToDo
-        return 0;
-    }
-
     /**
      * Select applet.
      *
@@ -124,61 +135,48 @@ public abstract class TPSProcessor {
      * 53 4C 42 47 49 4E 41
      *
      * @throws IOException
+     * @throws TPSException
      *
      */
 
-    protected int selectApplet(byte p1, byte p2, TPSBuffer aid) throws IOException {
+    protected APDUResponse selectApplet(byte p1, byte p2, TPSBuffer aid) throws IOException, TPSException {
 
         CMS.debug("In TPS_Processor.SelectApplet.");
-        int rc = RESULT_ERROR;
-
-        //Test data until we can read the CFG
 
-        if (aid.size() == 0) {
-            return RESULT_ERROR;
+        if (aid == null || aid.size() == 0) {
+            throw new TPSException("TPSProcessor.selectApplet: Invalid aid value!",
+                    TPSStatus.STATUS_ERROR_SECURE_CHANNEL);
         }
 
         Select select_apdu = new Select(p1, p2, aid);
 
-        APDUResponse respApdu = handleAPDURequest(select_apdu);
-
-        if (checkTokenPDUResponse(respApdu) == true) {
-            rc = RESULT_NO_ERROR;
-        }
-
-        return rc;
+        //return the Response because the caller can
+        //decide what to do, not every failure is fatal.
+        //For instance the coolkey applet may not yet exist.
+        return handleAPDURequest(select_apdu);
 
     }
 
-    protected TPSBuffer getStatus() throws IOException {
+    protected TPSBuffer getStatus() throws IOException, TPSException {
 
         CMS.debug("In TPS_Processor.GetStatus.");
 
-        TPSBuffer result = null;
-
         GetStatus get_status_apdu = new GetStatus();
 
-        APDUResponse respApdu = handleAPDURequest(get_status_apdu);
-
-        if (respApdu != null) {
-            result = respApdu.getData();
-        }
-
-        return result;
+        return handleAPDURequest(get_status_apdu).getData();
     }
 
-    protected APDUResponse handleAPDURequest(APDU apdu) throws IOException {
-        APDUResponse response = null;
+    protected APDUResponse handleAPDURequest(APDU apdu) throws IOException, TPSException {
 
-        if (session == null || apdu == null) {
-            return response;
+        if (apdu == null) {
+            throw new TPSException("TPSProcessor.handleAPDURequest: invalid incoming apdu!");
         }
 
         TokenPDURequest request_msg = new TokenPDURequest(apdu);
 
         try {
             session.write(request_msg);
-        } catch (Exception e) {
+        } catch (IOException e) {
             CMS.debug("TPS_Processor.HandleAPDURequest failed WriteMsg: " + e.toString());
             throw new IOException(e);
 
@@ -188,36 +186,32 @@ public abstract class TPSProcessor {
 
         try {
             response_msg = (TokenPDUResponse) session.read();
-        } catch (Exception e) {
+        } catch (IOException e) {
             CMS.debug("TPS_Processor.HandleAPDURequest failed ReadMsg: " + e.toString());
             throw new IOException(e);
 
         }
 
-        response = response_msg.getResponseAPDU();
-
-        if (checkTokenPDUResponse(response) == true) {
-            CMS.debug("TPS_Processor.HandleAPDURequest : apdu response is success");
-        } else {
-            CMS.debug("TPS_Processor.HandleAPDURequest: apdu response is failure.");
-        }
-
-        return response;
-
+        return response_msg.getResponseAPDU();
     }
 
-    protected TPSBuffer getCplcData() throws IOException {
+    protected TPSBuffer getCplcData() throws IOException, TPSException {
         CMS.debug("In TPS_Processor.GetData");
-        TPSBuffer result = null;
 
         GetData get_data_apdu = new GetData();
 
         APDUResponse respApdu = handleAPDURequest(get_data_apdu);
 
-        result = respApdu.getData();
+        if (!respApdu.checkResult()) {
+            throw new TPSException("TPSProcessor.getCplcData: Can't get data!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL);
+        }
+        TPSBuffer cplcData = respApdu.getData();
 
-        return result;
+        if (cplcData.size() != CPLC_DATA_SIZE) {
+            throw new TPSException("TPSProcessor.cplcData: Data invalid size!", TPSStatus.STATUS_ERROR_SECURE_CHANNEL);
+        }
 
+        return respApdu.getData();
     }
 
     protected TPSBuffer getAppletVersion() throws IOException, TPSException {
@@ -230,7 +224,7 @@ public abstract class TPSProcessor {
 
         APDUResponse respApdu = handleAPDURequest(get_version_apdu);
 
-        if (checkTokenPDUResponse(respApdu) != true) {
+        if (!respApdu.checkResult()) {
             CMS.debug("TPSProcessor.getAppletVersion: No applet version found on card!");
             return null;
         }
@@ -250,13 +244,13 @@ public abstract class TPSProcessor {
 
     }
 
-    protected String upgradeApplet(String operation, String tokenType, String new_version, SecurityLevel securityLevel,
+    protected String upgradeApplet(String operation, String new_version, SecurityLevel securityLevel,
             Map<String, String> extensions, int startProgress, int endProgress) throws TPSException {
 
         String newVersion = null;
         boolean appletUpgraded = false;
 
-        String directory = getAppletDirectory(operation, tokenType);
+        String directory = getAppletDirectory(operation);
 
         CMS.debug("TPSProcessor.upgradeApplet: applet target directory: " + directory);
 
@@ -269,7 +263,7 @@ public abstract class TPSProcessor {
         return newVersion;
     }
 
-    protected TPSStatus format(BeginOp message) throws TPSException, IOException {
+    protected void format(BeginOp message) throws TPSException, IOException {
 
         IConfigStore configStore = CMS.getConfigStore();
 
@@ -284,6 +278,7 @@ public abstract class TPSProcessor {
         boolean isExternalReg = false;
 
         try {
+            //These defaults are well known, it is safe to use them.
             CardManagerAID = configStore.getString(TPSEngine.CFG_APPLET_CARDMGR_INSTANCE_AID,
                     TPSEngine.CFG_DEF_CARDMGR_INSTANCE_AID);
             NetKeyAID = configStore.getString(TPSEngine.CFG_APPLET_NETKEY_INSTANCE_AID,
@@ -292,53 +287,27 @@ public abstract class TPSProcessor {
             this.isExternalReg = configStore.getBoolean(External_Reg_Cfg, false);
             CMS.debug("In TPS_Processor.Format isExternalReg: " + isExternalReg);
         } catch (EBaseException e1) {
-            CMS.debug("TPS_Processor.Format: Error obtaining mandatory config values.");
+            CMS.debug("TPS_Processor.Format: Internal Error obtaining mandatory config values. Error: " + e1);
             throw new TPSException("TPS error getting config values from config store.",
                     TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
         }
 
-        TPSStatus ret = TPSStatus.STATUS_NO_ERROR;
-
         TPSBuffer aidBuf = new TPSBuffer(CardManagerAID);
 
-        int select_rc = RESULT_NO_ERROR;
-
-        select_rc = selectApplet((byte) 0x04, (byte) 0x00, aidBuf);
+        APDUResponse select = selectApplet((byte) 0x04, (byte) 0x00, aidBuf);
 
-        if (select_rc == RESULT_ERROR) {
-            ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-            return ret;
+        if (!select.checkResult()) {
+            throw new TPSException("TPSProcessor.format: Can't selelect the card manager!");
         }
 
         TPSBuffer cplc_data = getCplcData();
-
-        if (cplc_data == null) {
-            ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-            return ret;
-        } else {
-            CMS.debug("cplc_data: " + cplc_data.toString());
-        }
+        CMS.debug("cplc_data: " + cplc_data.toString());
 
         TPSBuffer token_cuid = extractTokenCUID(cplc_data);
+        String cuid = token_cuid.toHexString();
 
-        String cuid = null;
-
-        if (token_cuid != null) {
-            cuid = token_cuid.toHexString();
-            CMS.debug("TPS_Processor.format: token_cuid str: " + cuid);
-        } else {
-            ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-            return ret;
-        }
-
-        TPSBuffer token_msn = extractTokenNSM(cplc_data);
-
-        String msn = null;
-
-        if (token_msn != null) {
-            msn = token_msn.toHexString();
-            CMS.debug("TPS_Processor.format: token_msn str: " + msn);
-        }
+        TPSBuffer token_msn = extractTokenMSN(cplc_data);
+        String msn = token_msn.toHexString();
 
         /**
          * Checks if the netkey has the required applet version.
@@ -346,38 +315,28 @@ public abstract class TPSProcessor {
 
         TPSBuffer netkeyAid = new TPSBuffer(NetKeyAID);
 
-        select_rc = RESULT_NO_ERROR;
+        // We don't care if the above fails now. getStatus will determine outcome.
 
-        select_rc = selectApplet((byte) 0x04, (byte) 0x00, netkeyAid);
+        select = selectApplet((byte) 0x04, (byte) 0x00, netkeyAid);
 
-        if (select_rc == RESULT_ERROR) {
-            ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-            return ret;
-        }
+        CMS.debug("TPSProcessor.format: First time select netkey applet: " + select.checkResult());
 
-        TPSBuffer status = getStatus();
+        TPSBuffer token_status = getStatus();
 
         byte major_version = 0x0;
         byte minor_version = 0x0;
         byte app_major_version = 0x0;
         byte app_minor_version = 0x0;
 
-        if (status != null) {
-            CMS.debug("TPS_Processor.format: status: " + status.toHexString());
-            major_version = status.at(0);
-            if (session == null) {
-                throw new TPSException("TPSProcessor.format, no TPSSession object specified!");
-            }
-            minor_version = status.at(1);
-            app_major_version = status.at(2);
-            app_minor_version = status.at(3);
-            CMS.debug("TPS_Processor.format: major_version " + major_version + " minor_version: " + minor_version
-                    + " app_major_version: " + app_major_version + " app_minor_version: " + app_minor_version);
-
-        } else {
-            ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-            return ret;
+        CMS.debug("TPS_Processor.format: status: " + token_status.toHexString());
+        if (token_status.size() >= 4) {
+            major_version = token_status.at(0);
+            minor_version = token_status.at(1);
+            app_major_version = token_status.at(2);
+            app_minor_version = token_status.at(3);
         }
+        CMS.debug("TPSProcessor.format: major_version " + major_version + " minor_version: " + minor_version
+                + " app_major_version: " + app_major_version + " app_minor_version: " + app_minor_version);
 
         if (isExternalReg) {
             //ToDo, do some external Reg stuff along with authentication
@@ -392,131 +351,105 @@ public abstract class TPSProcessor {
 
         //Now check provided profile
 
-        boolean profileStatusOK = checkProfileStateOK(tokenType);
-
-        if (profileStatusOK == false) {
-            CMS.debug("TPSProcessor.format: profile is disabled for profile: " + tokenType + " cuid: " + cuid);
-            ret = TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND;
-            return ret;
-        }
+        checkProfileStateOK();
 
         if (engine.isTokenPresent(cuid)) {
             //ToDo
 
         } else {
-
-            boolean allowUnknown = checkAllowUnknownToken(TPSEngine.OP_FORMAT_PREFIX);
-
-            if (allowUnknown == false) {
-                CMS.debug("TPSProcessor.format: Can not allow an unknown token.");
-                ret = TPSStatus.STATUS_ERROR_DISABLED_TOKEN;
-            }
-
+            checkAllowUnknownToken(TPSEngine.OP_FORMAT_PREFIX);
         }
 
         TPSBuffer build_id = getAppletVersion();
 
         if (build_id == null) {
-
-            boolean allowNoApplet = checkAllowNoAppletToken(TPSEngine.OP_FORMAT_PREFIX, tokenType);
-
-            if (allowNoApplet == false) {
-                CMS.debug("TPSProcessor.format: tokenw with no applet not allowed, exiting.");
-                ret = TPSStatus.STATUS_ERROR_SECURE_CHANNEL;
-                return ret;
-            }
-
+            checkAllowNoAppletToken(TPSEngine.OP_FORMAT_PREFIX);
         } else {
             appletVersion = Integer.toHexString(app_major_version) + "." + Integer.toHexString(app_minor_version) + "."
                     + build_id.toHexString();
         }
 
-        String appletRequiredVersion = checkForAppletUpgrade(TPSEngine.OP_FORMAT_PREFIX, tokenType);
+        String appletRequiredVersion = checkForAppletUpgrade(TPSEngine.OP_FORMAT_PREFIX);
 
         CMS.debug("TPSProcessor.format: appletVersion found: " + appletVersion + "requiredVersion: "
                 + appletRequiredVersion);
 
         SecurityLevel secLevel = SecurityLevel.SECURE_MSG_MAC_ENC;
 
-        String newKeyVersion = upgradeApplet(TPSEngine.OP_FORMAT_PREFIX, tokenType, appletRequiredVersion, secLevel,
+        String newKeyVersion = upgradeApplet(TPSEngine.OP_FORMAT_PREFIX, appletRequiredVersion, secLevel,
                 message.getExtensions(),
                 10, 90);
 
         CMS.debug("TPSProcessor.format: upgraded aplet version: " + newKeyVersion);
-        return ret;
     }
 
-    boolean checkProfileStateOK(String tokenType) throws TPSException {
+    void checkProfileStateOK() throws TPSException {
 
-        boolean result = true;
         IConfigStore configStore = CMS.getConfigStore();
 
-        String profileConfig = "config.Profiles." + tokenType + ".state";
+        String profileConfig = "config.Profiles." + selectedTokenType + ".state";
         String profileState = null;
 
         try {
-            profileState = configStore.getString(profileConfig);
-        } catch (EPropertyNotFound e) {
-            CMS.debug("TPSProcessor.checkProfileStateOK:  getting profileState, assuming entry does not exist, continuing! "
-                    + e);
+            profileState = configStore.getString(profileConfig, TPSEngine.CFG_ENABLED);
         } catch (EBaseException e) {
             //Default TPSException will return a "contact admin" error code.
             throw new TPSException(
                     "TPSProcessor.checkProfileStateOK: internal error in getting profile state from config.");
         }
 
-        if (profileState != null && !profileState.equals("Enabled")) {
+        if (!profileState.equals(TPSEngine.CFG_ENABLED)) {
             CMS.debug("TPSProcessor.checkProfileStateOK: profile specifically disabled.");
-            result = false;
+            throw new TPSException("TPSProcessor.checkProfileStateOK: profile disabled!");
         }
 
-        return result;
-
     }
 
-    boolean checkAllowNoAppletToken(String operation, String tokenType) throws TPSException {
+    void checkAllowNoAppletToken(String operation) throws TPSException {
         boolean allow = true;
         IConfigStore configStore = CMS.getConfigStore();
 
-        String noAppletConfig = operation + "." + tokenType + "." + TPSEngine.CFG_ALLOW_NO_APPLET;
+        String noAppletConfig = operation + "." + selectedTokenType + "." + TPSEngine.CFG_ALLOW_NO_APPLET;
 
         try {
-            allow = configStore.getBoolean(noAppletConfig);
-        } catch (EPropertyNotFound e) {
-            CMS.debug("TPSProcessor.checkAllowNoAppletToken: config param not found. Continuing..");
-
+            allow = configStore.getBoolean(noAppletConfig, true);
         } catch (EBaseException e) {
-            throw new TPSException("PSProcessor.checkAllowNoAppletToken: Internal error getting config param.");
+            throw new TPSException("TPSProcessor.checkAllowNoAppletToken: Internal error getting config param.");
+        }
+
+        if (!allow) {
+            throw new TPSException("TPSProcessor.checkAllowNoAppletToken: token without applet not permitted!",
+                    TPSStatus.STATUS_ERROR_CONTACT_ADMIN);
         }
-        CMS.debug("TPSProcessor.checkAllowNoAppletToken: returning: " + allow);
 
-        return allow;
     }
 
-    protected String checkForAppletUpgrade(String operation, String tokenType) throws TPSException {
+    protected String checkForAppletUpgrade(String operation) throws TPSException {
         String requiredVersion = null;
         IConfigStore configStore = CMS.getConfigStore();
 
-        String appletRequiredConfig = operation + "." + tokenType + "." + TPSEngine.CFG_APPLET_UPDATE_REQUIRED_VERSION;
+        String appletRequiredConfig = operation + "." + selectedTokenType + "."
+                + TPSEngine.CFG_APPLET_UPDATE_REQUIRED_VERSION;
 
         try {
-            requiredVersion = configStore.getString(appletRequiredConfig);
-        } catch (EPropertyNotFound e) {
-            throw new TPSException("TPSProcessor.checkForAppletUpgrade: Can't find applet required Version.",
-                    TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
-
+            requiredVersion = configStore.getString(appletRequiredConfig, null);
         } catch (EBaseException e) {
             throw new TPSException(
                     "TPSProcessor.checkForAppletUpgrade: Can't find applet required Version. Internal error obtaining version.",
                     TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
         }
 
+        if (requiredVersion == null) {
+            throw new TPSException("TPSProcessor.checkForAppletUpgrade: Can't find applet required Version.",
+                    TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
+        }
+
         CMS.debug("TPSProcessor.checkForAppletUpgrade: returning: " + requiredVersion);
 
         return requiredVersion;
     }
 
-    protected boolean checkAllowUnknownToken(String operation) throws TPSException {
+    protected void checkAllowUnknownToken(String operation) throws TPSException {
         boolean allow = true;
 
         IConfigStore configStore = CMS.getConfigStore();
@@ -524,32 +457,34 @@ public abstract class TPSProcessor {
         String unknownConfig = operation + "." + TPSEngine.CFG_ALLOW_UNKNOWN_TOKEN;
 
         try {
-            allow = configStore.getBoolean(unknownConfig);
-        } catch (EPropertyNotFound e) {
-            CMS.debug("TPSProcessor.checkAllowUnknownToken: config value not found continue..");
+            allow = configStore.getBoolean(unknownConfig, true);
         } catch (EBaseException e) {
             throw new TPSException("TPSProcessor.checkAllowUnknownToken: Internal error getting config value.");
         }
 
-        CMS.debug("checkAllowUnknownToken: returning: " + allow);
-        return allow;
+        if (allow == false) {
+            throw new TPSException(
+                    "TPSProcessor.checkAllowUnknownToken: Unknown tokens not allowed for this operation!",
+                    TPSStatus.STATUS_ERROR_TOKEN_DISABLED);
+        }
 
     }
 
-    protected String getAppletDirectory(String operation, String tokenType) throws TPSException {
-        String directory = null;
+    protected String getAppletDirectory(String operation) throws TPSException {
 
         IConfigStore configStore = CMS.getConfigStore();
+        String directory = null;
 
-        String directoryConfig = operation + "." + tokenType + "." + TPSEngine.CFG_APPLET_DIRECTORY;
+        String directoryConfig = operation + "." + selectedTokenType + "." + TPSEngine.CFG_APPLET_DIRECTORY;
 
+        //We need a directory
         try {
-            directory = configStore.getString(directoryConfig, null);
+            directory = configStore.getString(directoryConfig);
         } catch (EPropertyNotFound e) {
-            throw new TPSException("TPSProcessor.getAppletDirctory: Required config param missing.",
+            throw new TPSException("TPSProcessor.getAppletDirectory: Required config param missing.",
                     TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
         } catch (EBaseException e) {
-            throw new TPSException("TPSProcessor.getAppletDirctory: Internal error finding config value.",
+            throw new TPSException("TPSProcessor.getAppletDirectory: Internal error finding config value.",
                     TPSStatus.STATUS_ERROR_UPGRADE_APPLET);
         }
 
@@ -557,33 +492,12 @@ public abstract class TPSProcessor {
         return directory;
     }
 
-    protected boolean checkTokenPDUResponse(APDUResponse response) {
-
-        boolean result = false;
-
-        if (response == null)
-            return result;
-
-        byte sw1 = response.getSW1();
-        byte sw2 = response.getSW2();
-
-        int int1 = sw1 & 0xff;
-        int int2 = sw2 & 0xff;
-
-        CMS.debug("checkTokenPDUResponse: sw1: " + "0x" + Util.intToHex(int1) + " sw2: " + "0x" + Util.intToHex(int2));
-
-        if (sw1 == (byte) 0x90 && sw2 == 0x0)
-            result = true;
-
-        return result;
-    }
-
     public boolean getIsExternalReg() {
         return isExternalReg;
     }
 
-    public TPSStatus process(BeginOp beginMsg) throws TPSException, IOException {
-        return TPSStatus.STATUS_NO_ERROR;
+    public void process(BeginOp beginMsg) throws TPSException, IOException {
+        format(beginMsg);
     }
 
     /* Return calculated token profile type.
@@ -594,38 +508,52 @@ public abstract class TPSProcessor {
         String tokenType = null;
         String mappingOrder = null;
 
+        if (selectedTokenType != null) {
+            CMS.debug("TPSProcessor.getTokenType: Calling this more than once. This is not needed!");
+            return selectedTokenType;
+        }
+
         IConfigStore configStore = CMS.getConfigStore();
-        String cuid_x = cuid;
 
         String configName = prefix + "." + TPSEngine.CFG_PROFILE_MAPPING_ORDER;
 
         try {
-            mappingOrder = configStore.getString(configName, null);
+            mappingOrder = configStore.getString(configName);
+        } catch (EPropertyNotFound e) {
+            throw new TPSException(
+                    "TPSProcessor.getTokenType: Token Type configuration incorrect! Mising mapping order!",
+                    TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
+
         } catch (EBaseException e1) {
             //The whole feature won't work if this is wrong.
             throw new TPSException(
-                    "TPSProcessor.getTokenType: Token Type configuration incorrect! Mising mapping order!",
+                    "TPSProcessor.getTokenType: Internal error obtaining config value.!",
                     TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
         }
 
-        String[] mappings = mappingOrder.split(",");
-
         String targetTokenType = null;
 
-        for (int i = 0; i < mappings.length; i++) {
+        for (String mappingId : mappingOrder.split(",")) {
 
-            String mappingId = mappings[i];
             CMS.debug("TPS_Processor::GetTokenType:  mapping: " + mappingId);
 
             String mappingConfigName = prefix + ".mapping." + mappingId + ".target.tokenType";
 
             CMS.debug("TPS_Processor::GetTokenType:  mappingConfigName: " + mappingConfigName);
 
+            //We need this to exist.
             try {
-                targetTokenType = configStore.getString(mappingConfigName, null);
+                targetTokenType = configStore.getString(mappingConfigName);
+            } catch (EPropertyNotFound e) {
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Token Type configuration incorrect! No target token type config value found! Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
+
             } catch (EBaseException e) {
                 throw new TPSException(
-                        "TPSProcessor.getTokenType: Token Type configuration incorrect! Invalid or no targetTokenType.",
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
                         TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
 
@@ -638,7 +566,11 @@ public abstract class TPSProcessor {
             try {
                 tokenType = configStore.getString(mappingConfigName, null);
             } catch (EBaseException e) {
-                tokenType = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
+
             }
 
             CMS.debug("TPS_Processor::GetTokenType:  targetTokenType: " + targetTokenType);
@@ -668,7 +600,10 @@ public abstract class TPSProcessor {
             try {
                 tokenATR = configStore.getString(mappingConfigName, null);
             } catch (EBaseException e) {
-                tokenATR = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
 
             CMS.debug("TPS_Processor::GetTokenType:  tokenATR: " + tokenATR);
@@ -698,14 +633,18 @@ public abstract class TPSProcessor {
 
             try {
                 tokenCUIDStart = configStore.getString(mappingConfigName, null);
+
             } catch (EBaseException e) {
-                tokenCUIDStart = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
 
             CMS.debug("TPS_Processor::GetTokenType:  tokenCUIDStart: " + tokenCUIDStart);
 
             if (tokenCUIDStart != null && tokenCUIDStart.length() > 0) {
-                if (cuid_x == null) {
+                if (cuid == null) {
                     continue;
                 }
 
@@ -713,7 +652,7 @@ public abstract class TPSProcessor {
                     continue;
                 }
 
-                if (cuid_x.compareTo(tokenCUIDStart) < 0) {
+                if (cuid.compareTo(tokenCUIDStart) < 0) {
                     continue;
                 }
 
@@ -727,13 +666,16 @@ public abstract class TPSProcessor {
             try {
                 tokenCUIDEnd = configStore.getString(mappingConfigName, null);
             } catch (EBaseException e) {
-                targetTokenType = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
 
             CMS.debug("TPS_Processor::GetTokenType:  tokenCUIDEnd: " + tokenCUIDEnd);
 
             if (tokenCUIDEnd != null && tokenCUIDEnd.length() > 0) {
-                if (cuid_x == null) {
+                if (cuid == null) {
                     continue;
                 }
 
@@ -741,7 +683,7 @@ public abstract class TPSProcessor {
                     continue;
                 }
 
-                if (cuid_x.compareTo(tokenCUIDEnd) > 0) {
+                if (cuid.compareTo(tokenCUIDEnd) > 0) {
                     continue;
                 }
 
@@ -757,15 +699,16 @@ public abstract class TPSProcessor {
             try {
                 majorVersion = configStore.getString(mappingConfigName, null);
             } catch (EBaseException e) {
-                majorVersion = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
 
             CMS.debug("TPS_Processor::GetTokenType:  majorVersion: " + majorVersion);
             if (majorVersion != null && majorVersion.length() > 0) {
 
-                int major = 0;
-
-                major = Integer.parseInt(majorVersion);
+                int major = Integer.parseInt(majorVersion);
 
                 if (major != major_version) {
                     continue;
@@ -779,15 +722,16 @@ public abstract class TPSProcessor {
             try {
                 minorVersion = configStore.getString(mappingConfigName, null);
             } catch (EBaseException e) {
-                minorVersion = null;
+                throw new TPSException(
+                        "TPSProcessor.getTokenType: Internal error obtaining config value. Config: "
+                                + mappingConfigName,
+                        TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
             }
             CMS.debug("TPS_Processor::GetTokenType:  minorVersion " + minorVersion);
 
             if (minorVersion != null && minorVersion.length() > 0) {
 
-                int minor = 0;
-
-                minor = Integer.parseInt(minorVersion);
+                int minor = Integer.parseInt(minorVersion);
 
                 if (minor != minor_version) {
                     continue;
@@ -805,6 +749,8 @@ public abstract class TPSProcessor {
                     TPSStatus.STATUS_ERROR_DEFAULT_TOKENTYPE_NOT_FOUND);
         }
 
+        //Set this once, it won't change for this session.
+        setSelectedTokenType(targetTokenType);
         return targetTokenType;
 
     }
-- 
1.8.3.1

