Package org.infotechservice.smartcard.service

Source Code of org.infotechservice.smartcard.service.SmartCard

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.infotechservice.smartcard.service;

import javax.smartcardio.Card;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import org.infotechservice.smartcard.utils.CardFrameworkException;
import org.infotechservice.smartcard.utils.Converter;

/**
* Объект инкапсулирующий смарткарту, создается на основе терминала,
* если в нем есть смарткарта
* @author Axe
*/
public class SmartCard {

    private final CardTerminal terminal;
    private Card card;

    /**
     * Создает объект сарткарты по терминалу, если в нем есть смарткарта
     * @param terminal
     * @return
     */
    public static SmartCard getInstance(CardTerminal terminal) {
        Card card = null;
        try {
            if (terminal.isCardPresent()) {
                card = terminal.connect("*");
            }
            if(card != null) {
                return new SmartCard(terminal, card);
            }
        } catch (Exception ex) {
            //do nothing
        }
        return null;
    }

    private SmartCard(CardTerminal terminal, Card card) {
        this.terminal = terminal;
        this.card = card;
    }

    public CardTerminal getTerminal() {
        return terminal;
    }

    public Card getCard() {
        return card;
    }

    /**
     * Возвращает ATR карты
     * @return
     */
    public CardAtr getAtr() {
        return new CardAtr(Converter.hexDump(card.getATR().getBytes()));
    }

    /**
     * Освобождает карту
     * @throws CardException
     */
    public void dispose() throws CardException {
        card.disconnect(true);
    }

    @Override
    public String toString() {
        return getAtr().toString();
    }

    /**
     * Включает режим эксклюзивного использования карты
     * @throws CardException
     */
    void beginExclusive() throws CardException {
        try {
            card.beginExclusive();
        } catch (IllegalStateException ex) {
            throw new CardFrameworkException("Ошибка при попытке получить доступ к карте, возможно карта уже используется", ex);
        }
    }

    /**
     * Выключает режим эксклюзивного использования карты
     * @param smartcard
     * @throws CardException
     */
    void endExclusive() throws CardException {
        try {
            card.endExclusive();
        } catch (IllegalStateException ex) {
            throw new IllegalStateException("General code error", ex);
        }
    }
}
TOP

Related Classes of org.infotechservice.smartcard.service.SmartCard

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.