Search in sources :

Example 16 with NFCException

use of net.rim.device.api.io.nfc.NFCException in project Samples-for-Java by blackberry.

the class NdefListenerManager method unRegisterListener.

public void unRegisterListener() {
    ReaderWriterManager nfcManager;
    try {
        nfcManager = ReaderWriterManager.getInstance();
        nfcManager.removeNDEFMessageListener(NDEFRecord.TNF_EXTERNAL, "my.rim.com:myrecordtype");
        Utilities.log("XXXX NfcReadNdefSmartTag remove NDEF Message Listener success");
        rts.replace(Constants.LISTENER_STATE_TOKEN, new Boolean(false));
    } catch (NFCException e) {
        Utilities.log("XXXX " + e.getClass().getName() + ":" + e.getMessage());
    }
}
Also used : NFCException(net.rim.device.api.io.nfc.NFCException) ReaderWriterManager(net.rim.device.api.io.nfc.readerwriter.ReaderWriterManager)

Example 17 with NFCException

use of net.rim.device.api.io.nfc.NFCException in project Samples-for-Java by blackberry.

the class NfcReadNdefSmartTagUpdate method diyParsing.

/*
     * This code has been replaced by the new 7.1 Helper classes. Kept here for reference purposes.
     */
private void diyParsing() {
    /*
         * The NDEF Message may consist of a number of NDEF records
         */
    NDEFRecord[] records = _message.getRecords();
    /*
         * This is the number of NDEF records in the NDEF message
         */
    int numRecords = records.length;
    Utilities.log("XXXX NfcReadNdefSmartTagUpdate in runnable #records=" + numRecords);
    /*
         * Only unpick the message if it contains a non-zero number of records
         */
    if (numRecords > 0) {
        /*
             * Work our way through each record in the message in turn
             */
        for (int j = numRecords - 1; j >= 0; j--) {
            Utilities.log("XXXX NfcReadNdefSmartTagUpdate processing NDEF record#=" + j);
            /*
                 * Extract the NDEF record payload as an array of bytes
                 * 
                 * This is an example of what an NDEF Smart Poster payload looks like representing:
                 * 
                 * Text (en_US): This is a title for the BBC URI URI : http://www.bbc.co.uk
                 * 
                 * Original length 59 decimal bytes
                 * 
                 * NDEF PayLoad:
                 * 
                 * 99 01 25 01 54 31 05 65 6E 2D :..%.T1.en-: 55 53 54 68 69 73 20 69 73 20 :USThis is : 61 20 74 69 74 6C 65 20
                 * 66 6F :a title fo: 72 20 74 68 65 20 42 42 43 20 :r the BBC : 55 52 49 59 01 0A 01 55 32 01 :URIY...U2.: 62 62
                 * 63 2E 63 6F 2E 75 6B :bbc.co.uk :
                 * 
                 * Notice that "http://www." is so common it has a special binary encoding and only the remainder of the URL is
                 * text encoded "bbc.co.uk"
                 */
            byte[] payloadBytes = records[j].getPayload();
            /*
                 * Parse and display
                 */
            StringBuffer hexPayload = new StringBuffer();
            StringBuffer characterPayload = new StringBuffer();
            String hexpair;
            int numberOfHexPairs = 8;
            for (int i = 0; i < payloadBytes.length; i++) {
                hexpair = byte2HexPair(payloadBytes[i]);
                characterPayload.append(byte2Ascii(payloadBytes[i]));
                hexPayload.append(hexpair + " " + (((i + 1) % numberOfHexPairs == 0) ? "\n" : ""));
                characterPayload.append((((i + 1) % numberOfHexPairs == 0) ? "\n" : ""));
            }
            /*
                 * Parse the elements of the NDEF record It should identify WELL_KNOWN, TEXT or URI and "Sp" for smart poster
                 */
            String record = "Root NDEF Record\nID: " + records[j].getId() + "\nType: " + records[j].getType() + "\nTNF: " + records[j].getTypeNameFormat() + "\nPayload Len: " + records[j].getPayload().length + "\nHex Payload: \n" + hexPayload + "\nCharacter Payload: \n" + characterPayload;
            _screen.logEvent(record);
            /*
                 * If we recognise this as a Smart Tag Type "Sp"
                 */
            if ("Sp".equals(records[j].getType())) {
                Utilities.log("XXXX NfcReadNdefSmartTagUpdate recognised a Smart Poster Message");
                try {
                    NDEFMessage smartPosterMessage = new NDEFMessage(records[j].getPayload());
                    NDEFRecord[] spRecords = smartPosterMessage.getRecords();
                    int numSpRecords = spRecords.length;
                    Utilities.log("XXXX NfcReadNdefSmartTagUpdate in runnable #records=" + numSpRecords);
                    if (numSpRecords > 0) {
                        Utilities.log("XXXX NfcReadNdefSmartTagUpdate processing Smart Poster Message");
                        for (int k = numSpRecords - 1; k >= 0; k--) {
                            Utilities.log("XXXX NfcReadNdefSmartTagUpdate processing SP record#=" + k);
                            byte[] spPayloadBytes = spRecords[k].getPayload();
                            hexPayload = new StringBuffer();
                            characterPayload = new StringBuffer();
                            for (int i = 0; i < spPayloadBytes.length; i++) {
                                hexpair = byte2HexPair(spPayloadBytes[i]);
                                characterPayload.append(byte2Ascii(spPayloadBytes[i]));
                                hexPayload.append(hexpair + " " + (((i + 1) % numberOfHexPairs == 0) ? "\n" : ""));
                                characterPayload.append((((i + 1) % numberOfHexPairs == 0) ? "\n" : ""));
                            }
                            String spRecordLog = "Subsidiary NDEF Record\nID: " + spRecords[k].getId() + "\nType: " + spRecords[k].getType() + "\nTNF: " + spRecords[k].getTypeNameFormat() + "\nPayload Len: " + spRecords[k].getPayload().length + "\nHex Payload: \n" + hexPayload + "\nCharacter Payload: \n" + characterPayload;
                            _screen.logEvent(spRecordLog);
                            if ((spRecords[k].getTypeNameFormat() == NDEFRecord.TNF_WELL_KNOWN) && "T".equals(spRecords[k].getType())) {
                                /*
                                     * Well Known Type "T" is a TEXT record
                                     */
                                String text = new String();
                                String langCode = new String();
                                // bit 7 indicates UTF-8 if 0, UTF-16 if 1. Bits 5..0 len
                                int statusByte = spPayloadBytes[0];
                                // of IANA language code.
                                boolean is_utf16 = Utilities.isUtf16Encoded(statusByte);
                                int iana_language_code_len = Utilities.getIanaLanguageCodeLength(statusByte);
                                // extract the IANA language code as an ASCII string
                                byte[] iana_lang_code_bytes = new byte[iana_language_code_len];
                                if (iana_language_code_len > 0) {
                                    for (int m = 0; m < iana_language_code_len; m++) {
                                        iana_lang_code_bytes[m] = spPayloadBytes[m + 1];
                                    }
                                }
                                langCode = new String(iana_lang_code_bytes, "US-ASCII");
                                // extract the text which may be UTF-8 or UTF-16 encoded depending on bit 7 of the status byte
                                byte[] text_bytes = new byte[spPayloadBytes.length - iana_language_code_len + 1];
                                int i = 0;
                                for (int m = iana_language_code_len + 1; m < spPayloadBytes.length; m++) {
                                    text_bytes[i] = spPayloadBytes[m];
                                    i++;
                                }
                                if (!is_utf16) {
                                    text = new String(text_bytes, "UTF-8");
                                } else {
                                    text = new String(text_bytes, "UTF-16");
                                }
                                _screen.logEvent("Language: " + langCode);
                                _screen.logEvent("Text: " + text);
                            } else if ((spRecords[k].getTypeNameFormat() == NDEFRecord.TNF_WELL_KNOWN) && "U".equals(spRecords[k].getType())) {
                                /*
                                     * Well Known Type "U" is a URI record
                                     */
                                StringBuffer urlBuffer = new StringBuffer();
                                int urlOffset = 1;
                                if (spPayloadBytes[0] == (byte) 0x01) {
                                    urlBuffer.append("http://www.");
                                } else if (spPayloadBytes[0] == (byte) 0x02) {
                                    urlBuffer.append("https://");
                                } else if (spPayloadBytes[0] == (byte) 0x03) {
                                    urlBuffer.append("http://");
                                } else if (spPayloadBytes[0] == (byte) 0x04) {
                                    urlBuffer.append("https://");
                                }
                                // extract the URI which must be UTF-8 encoded
                                byte[] uri_bytes = new byte[spPayloadBytes.length - 1];
                                int i = 0;
                                for (int m = urlOffset; m < spPayloadBytes.length; m++) {
                                    uri_bytes[i] = spPayloadBytes[m];
                                    i++;
                                }
                                urlBuffer.append(new String(uri_bytes, "UTF-8"));
                                _screen.logEvent("URL: " + urlBuffer);
                            }
                        }
                    } else {
                        Utilities.log("XXXX NfcReadNdefSmartTagUpdate empty Smart Poster Message");
                    }
                } catch (BadFormatException e) {
                    Utilities.log("XXXX NfcReadNdefSmartTagUpdate bad NDEF format message");
                    e.printStackTrace();
                } catch (NFCException e) {
                    Utilities.log("XXXX NfcReadNdefSmartTagUpdate NFC Exception");
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    Utilities.log("XXXX NfcReadNdefSmartTagUpdate UnsupportedEncodingException");
                    e.printStackTrace();
                }
            }
        }
    } else {
        Utilities.log("XXXX NfcReadNdefSmartTagUpdate no records in message");
        _screen.logEvent("This is not the tag you're looking for!\n" + "It contains no records!\n" + "You should search elsewhere!");
    }
}
Also used : NDEFRecord(net.rim.device.api.io.nfc.ndef.NDEFRecord) NFCException(net.rim.device.api.io.nfc.NFCException) NDEFMessage(net.rim.device.api.io.nfc.ndef.NDEFMessage) BadFormatException(net.rim.device.api.io.nfc.ndef.BadFormatException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 18 with NFCException

use of net.rim.device.api.io.nfc.NFCException in project Samples-for-Java by blackberry.

the class ToggleCeCommand method execute.

public void execute(ReadOnlyCommandMetadata metadata, Object context) {
    NfcTransScreen screen = NfcTransScreen.getInstance();
    Utilities.log("XXXX " + Thread.currentThread().getName() + " toggling card emulation");
    boolean nfc_enabled = false;
    try {
        nfc_enabled = nfc_service.isNfcEnabled();
        screen.setNfcLed(Utilities.ledBooleanToInt(nfc_enabled));
    } catch (NFCException e) {
        Utilities.log("XXXX " + Thread.currentThread().getName() + " exception when establishing NFC service status: " + e.getClass().getName() + ":" + e.getMessage());
        screen.setUserMessage("Failed to establish NFC service status");
        screen.setNfcLed(Constants.LED_ERR);
        return;
    }
    if (!nfc_enabled) {
        Utilities.log("XXXX " + Thread.currentThread().getName() + " NFC seems to be OFF so prompting user to enable it");
        screen.setUserMessage("NFC is off");
        try {
            nfc_service.promptToEnableNFC();
            screen.setCeButtonState(ce.isCeEnabled(SecureElement.BATTERY_ON_MODE));
        } catch (NFCException e) {
            Utilities.log("XXXX " + Thread.currentThread().getName() + " exception when prompting to enable NFC: " + e.getClass().getName() + ":" + e.getMessage());
            screen.setUserMessage("Failed when prompting to enable NFC");
        }
        return;
    }
    boolean ce_enabled = false;
    try {
        ce_enabled = ce.isCeEnabled(SecureElement.BATTERY_ON_MODE);
    } catch (NFCException e1) {
        Utilities.log("XXXX " + Thread.currentThread().getName() + " exception when checking CE status: " + e1.getClass().getName() + ":" + e1.getMessage());
        screen.setUserMessage("Error: could not establish CE status");
        screen.setCemLed(Constants.LED_ERR);
        return;
    }
    if (!ce_enabled) {
        try {
            if (nfc_service.isNfcEnabled()) {
                Utilities.log("XXXX " + Thread.currentThread().getName() + " NFC is ON so setting technology types");
                // Route ISO14443x to the Secure Element
                // for battery on, device on mode
                ce_enabled = ce.setRoutingOn(ce.getCurrentTechnologyTypes());
                if (ce_enabled) {
                    screen.setCeButtonState(true);
                    screen.setSelectButtonState(true);
                    screen.setUserMessage("Card emulation enabled OK");
                    screen.setCemLed(Constants.LED_ON);
                } else {
                    screen.setUserMessage("Card emulation not enabled");
                }
            } else {
                Utilities.log("XXXX " + Thread.currentThread().getName() + " NFC seems to be OFF so prompting user to enable it");
                screen.setUserMessage("NFC is off");
                nfc_service.promptToEnableNFC();
            }
        } catch (NFCException e) {
            Utilities.log("XXXX " + Thread.currentThread().getName() + " exception when setting SE routing: " + e.getClass().getName() + ":" + e.getMessage());
            screen.setUserMessage("Failed to set NFC routing");
            return;
        }
    } else {
        try {
            // Remove routing
            Utilities.log("XXXX " + Thread.currentThread().getName() + " NFC removing NFC SIM SE routing");
            ce_enabled = ce.setRoutingOff();
            if (!ce_enabled) {
                screen.setCeButtonState(false);
                screen.setSelectButtonState(false);
                screen.setUserMessage("Card emulation disabled OK");
                screen.setCemLed(Constants.LED_OFF);
            } else {
                screen.setUserMessage("Card emulation not disabled");
            }
        } catch (NFCException e) {
            Utilities.log("XXXX " + Thread.currentThread().getName() + " exception when setting SE routing: " + e.getClass().getName() + ":" + e.getMessage());
            screen.setUserMessage("Failed to set NFC routing");
            return;
        }
    }
}
Also used : NFCException(net.rim.device.api.io.nfc.NFCException) NfcTransScreen(nfc.sample.nfctransaction.ui.NfcTransScreen)

Example 19 with NFCException

use of net.rim.device.api.io.nfc.NFCException in project Samples-for-Java by blackberry.

the class CardEmulation method registerTransactionListener.

public static void registerTransactionListener(TransactionListener tl) {
    int pid = ApplicationManager.getApplicationManager().getProcessId(ApplicationDescriptor.currentApplicationDescriptor());
    Settings settings = Settings.getInstance();
    SecureElementManager sem = SecureElementManager.getInstance();
    if (sem == null) {
        Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " SecureElementManager instance is null - exiting");
        System.exit(0);
    }
    SecureElement[] sec_elements = null;
    try {
        sec_elements = sem.getSecureElements();
    } catch (NFCException e2) {
        e2.printStackTrace();
    }
    if (sec_elements == null) {
        Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " SecureElement[] is null - exiting");
        System.exit(0);
    }
    Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " device has " + sec_elements.length + " SEs");
    Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " getting SecureElement instance");
    SecureElement se = null;
    try {
        if (settings.isSimSeSelected()) {
            Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " Obtaining SecureElement in SIM");
            se = sem.getSecureElement(SecureElement.SIM);
        } else {
            Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " Obtaining embedded SecureElement");
            se = sem.getSecureElement(SecureElement.EMBEDDED);
        }
    } catch (NFCException e1) {
        Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " exception when getting SE: " + e1.getClass().getName() + ":" + e1.getMessage());
    }
    if (se == null) {
        Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " SecureElement is null - exiting");
        System.exit(0);
    }
    // register our app as a transaction listener
    try {
        Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " adding transaction listener for AID:" + settings.getRegisteredAIDAsString());
        se.addTransactionListener(tl, new byte[][] { settings.getRegisteredAID() });
        _tl = tl;
    } catch (NFCException e) {
        if (!e.getMessage().startsWith("TransactionListener has already been added")) {
            Utilities.log("XXXX " + pid + ":" + Thread.currentThread().getName() + " exception when adding transaction listener: " + e.getClass().getName() + ":" + e.getMessage());
            System.exit(0);
        }
    }
}
Also used : NFCException(net.rim.device.api.io.nfc.NFCException) SecureElement(net.rim.device.api.io.nfc.se.SecureElement) SecureElementManager(net.rim.device.api.io.nfc.se.SecureElementManager) Settings(nfc.sample.nfctransaction.Settings)

Example 20 with NFCException

use of net.rim.device.api.io.nfc.NFCException in project Samples-for-Java by blackberry.

the class DetectionListenerManager method registerListener.

public void registerListener(NfcWriteNdefSmartTagListener nfcWriteNdefSmartTagListener) {
    ReaderWriterManager nfcManager;
    Utilities.log("XXXX NfcWriteNdefSmartTag about to add Detection Listener");
    try {
        nfcManager = ReaderWriterManager.getInstance();
        nfcManager.addDetectionListener(nfcWriteNdefSmartTagListener, new int[] { Target.NDEF_TAG });
        Utilities.log("XXXX NfcWriteNdefSmartTag add Detection Listener success");
        logEvent("Detection Listener added");
        rts.replace(Constants.LISTENER_STATE_TOKEN, new Boolean(true));
    } catch (NFCException e) {
        e.printStackTrace();
        Utilities.log("XXXX NfcWriteNdefSmartTag NFCException on register");
        logEvent("Detection Listener add failed");
    }
}
Also used : NFCException(net.rim.device.api.io.nfc.NFCException) ReaderWriterManager(net.rim.device.api.io.nfc.readerwriter.ReaderWriterManager)

Aggregations

NFCException (net.rim.device.api.io.nfc.NFCException)24 ReaderWriterManager (net.rim.device.api.io.nfc.readerwriter.ReaderWriterManager)8 ProtocolMessageMasterBid (nfc.sample.tictactoe.protocol.ProtocolMessageMasterBid)5 NDEFMessage (net.rim.device.api.io.nfc.ndef.NDEFMessage)4 IOException (java.io.IOException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 NDEFRecord (net.rim.device.api.io.nfc.ndef.NDEFRecord)2 SecureElement (net.rim.device.api.io.nfc.se.SecureElement)2 SecureElementManager (net.rim.device.api.io.nfc.se.SecureElementManager)2 MainScreen (net.rim.device.api.ui.container.MainScreen)2 VirtualISO14443Part4TypeATarget (net.rim.device.api.io.nfc.emulation.VirtualISO14443Part4TypeATarget)1 BadFormatException (net.rim.device.api.io.nfc.ndef.BadFormatException)1 NDEFTagConnection (net.rim.device.api.io.nfc.ndef.NDEFTagConnection)1 SmartPosterRecord (net.rim.device.api.io.nfc.ndef.rtd.SmartPosterRecord)1 Settings (nfc.sample.nfctransaction.Settings)1 CardEmulation (nfc.sample.nfctransaction.nfc.CardEmulation)1 NfcTransScreen (nfc.sample.nfctransaction.ui.NfcTransScreen)1 GameProtocol (nfc.sample.tictactoe.protocol.GameProtocol)1 ProtocolMessageResetBidState (nfc.sample.tictactoe.protocol.ProtocolMessageResetBidState)1 ProtocolMessageTurnOver (nfc.sample.tictactoe.protocol.ProtocolMessageTurnOver)1