look for supported cards across all connected card terminals

This commit is contained in:
Craig Raw 2023-05-31 14:25:45 +02:00
parent dbbeaf67b6
commit 98d9a6882b
2 changed files with 28 additions and 7 deletions

View file

@ -17,6 +17,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CardTerminals;
import javax.smartcardio.TerminalFactory;
import java.io.File;
@ -90,11 +91,15 @@ public abstract class CardApi {
public abstract void disconnect();
public static boolean isReaderAvailable() {
return !getAvailableTerminals().isEmpty();
}
public static List<CardTerminal> getAvailableTerminals() {
setLibrary();
try {
TerminalFactory tf = TerminalFactory.getDefault();
return !tf.terminals().list().isEmpty();
return tf.terminals().list();
} catch(Exception e) {
Throwable cause = Throwables.getRootCause(e);
if(cause.getMessage().equals("SCARD_E_NO_SERVICE")) {
@ -106,7 +111,7 @@ public abstract class CardApi {
}
}
return false;
return Collections.emptyList();
}
private static void recoverNoService() {

View file

@ -20,8 +20,7 @@ import org.slf4j.LoggerFactory;
import javax.smartcardio.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.*;
import java.util.Map;
public class CardTransport {
@ -41,15 +40,32 @@ public class CardTransport {
throw new IllegalStateException("No reader connected");
}
CardTerminal cardTerminal = (CardTerminal)terminals.get(0);
connection = cardTerminal.connect("*");
Card connection = null;
for(Iterator<CardTerminal> iter = terminals.iterator(); iter.hasNext(); ) {
try {
connection = getConnection(iter.next());
break;
} catch(CardException e) {
if(!iter.hasNext()) {
log.error(e.getMessage());
throw e;
}
}
}
this.connection = connection;
}
private Card getConnection(CardTerminal cardTerminal) throws CardException {
Card connection = cardTerminal.connect("*");
CardChannel cardChannel = connection.getBasicChannel();
ResponseAPDU resp = cardChannel.transmit(new CommandAPDU(0, 0xA4, 4, 0, Utils.hexToBytes(APPID.toUpperCase())));
if(resp.getSW() != SW_OKAY) {
log.error("Card initialization error, response was 0x" + Integer.toHexString(resp.getSW()));
throw new CardException("Card initialization error, response was 0x" + Integer.toHexString(resp.getSW()) + ". Note that only the Tapsigner is currently supported.");
}
return connection;
}
JsonObject send(String cmd, Map<String, Object> args) throws CardException {