Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 44

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 44 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 442018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 44)

However, if it exceeds the value ofTransmitMTU, any additional data will be discarded.To read a packet of data from an L2CAPConnection we call:public int receive(byte[] inBuf)The packet will be read into the inBuf byte array. The size ofinBuf should at least be equal to ReceiveMTU to avoid loss of data.L2CAPConnection also provides the ready() method:public boolean ready()If ready() returns true, a packet of data is available to be receivedand we can call receive without blocking.SECURITY2274.5 SecuritySecurity is an important aspect of Bluetooth communication. JSR 82provides various security options to prevent unauthorized access to aBluetooth device and to provide secure communication between devicesusing data encryption.4.5.1AuthenticationAuthentication refers to the process of verifying the identity of a remotedevice.

The authentication mechanism in Bluetooth is based on a PINnumber shared between devices.A Bluetooth server can require client authentication by adding theoptional authenticate=true parameter to the connection URL, asshown below.String url =“btspp://localhost:00001111222233334444555566667777;authenticate=true”StreamConnectionNotifier service =(StreamConnectionNotifier)Connector.open(url);Similarly, clients can request server authentication in the connection URL. In the absence of the authenticate=true parameter,either client or server can, at any time after establishing an connection, request remote device authentication via the authenticate()method of RemoteDevice.On Symbian OS, if authentication of a remote device is requestedthe system will display a pop-up dialog on the local device requestingthe user to enter a PIN number (see Figure 4.5) that is shared with theFigure 4.5 Bluetooth authentication on the Nokia 6600.228JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYuser of the remote device.

The remote device will prompt its user for theshared PIN, and only if the PIN codes on both devices match will theauthentication process succeed. Note that the PIN number itself is nottransmitted between devices, instead a 128-bit key derived from the PINnumber is used.A device may determine if a remote device has been authenticatedby invoking the isAuthenticated() method of RemoteDevice. Areturn value of true indicates that the remote device has previously beenauthenticated. Note that authentication is not specific to a particular connection. The remote device may have been authenticated by a previousconnection or even another application.4.5.2AuthorizationBluetooth authorization is the process by which a server device grants aspecific client access to a specific service it offers. A server can require thatclients be authorized by adding the authorize=true parameter to theconnection URL.

Note that authorization also requires authentication sosome parameter combinations (e.g. authenticate=false;authorize=true) are forbidden and will result in a BluetoothConnectionException.If authorization was not requested in the connection URL, the servercan request client authorization via the authorize() method of theRemoteDevice.On Symbian OS, dynamic authorization is granted to a specific remotedevice by the user for each connection request. A dialog box prompts theuser to accept or reject the connection (see Figure 4.6).In addition, current Symbian OS devices allow static authorization bythe user of a paired remote device via the system Bluetooth control panelFigure 4.6Bluetooth authorization on the Nokia 6600.JAVA BLUETOOTH API AND THE MIDP 2.0 SECURITY MODEL229(the BCC, in JSR terminology).

The remote device becomes trusted and allincoming connections from it are authorized until the static authorizationis revoked via the Bluetooth control panel.A server device can determine if a remote device has previouslybeen authorized by invoking the isAuthorized() method of the RemoteDevice. A return value of true indicates the server side connectionto the remote device has been authorized.4.5.3 EncryptionEncryption is used in Bluetooth communication to protect sensitive datafrom eavesdropping. Either client or server can require that a connectionis encrypted by adding the encrypt=true parameter to the connection URL.

Note that encryption requires the previous authenticationof the remote device so some parameter combinations (e.g. authenticate=false;encrypt=true) are forbidden and will result in aBluetoothConnectionException.After establishing an unencrypted connection, it is possible to requirefurther communication to be encrypted by using the encrypt() methodof the RemoteDevice. Encryption is performed transparently by theimplementation using a symmetric encryption algorithm.A device can determine whether communication with a remote deviceis currently encrypted by invoking the isEncrypted() method of theRemoteDevice. A return value of true indicates that data exchangewith the remote device is encrypted. Note that encryption of the data linkwith a remote device is not specific to a particular connection and mayhave enabled by a previous connection or even application.4.6 Java Bluetooth API and the MIDP 2.0 Security ModelA signed MIDlet suite which contains MIDlets that open Bluetoothconnections must explicitly request the appropriate permission in itsMIDlet-Permissions attribute.

To make outgoing (client) connectionsthe MIDlet suite must request the javax.microedition.io.Connector.bluetooth.client permission. To accept incoming (server)connections the MIDlet suite must request the javax.microedition.io.Connector.bluetooth.server permission. For example, theMIDlet-Permissions attribute entry in the JAD file may be as follows.MIDlet-Permissions: javax.microedition.io.Connector.bluetooth.client,javax.microedition.io.Connector.bluetooth.serverIf the protection domain to which the signed MIDlet suite would bebound grants, or potentially grants, the requested permissions, the MIDletsuite can be installed and the MIDlets it contains will be able to open230JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYBluetooth client and server connections, either automatically or withexplicit user permission, depending upon the security policy in effect.The Bluetooth protected APIs form part of the Local Connectivityfunction group as defined in the Recommended Security Policy forGSM/UMTS Compliant Devices addendum to the MIDP 2.0 specification.The Sony Ericsson P900/P908 supports the trusted protection domain (onOrganiser firmware versions R2B02 or later).

The security policy in effectfor MIDlets in MIDlet suites bound to the trusted protection domain on theP900/P908 allows automatic access to the Local Connectivity functiongroup. At the time of writing, the available firmware release (3.42.1)on the Nokia 6600 only supports the untrusted domain, although futurereleases will add support for trusted protection domains.Whether MIDlets in untrusted MIDlet suites can open Bluetooth connections depends on the security policy relating to the Local Connectivityfunction group for the untrusted domain in force on the device. On theNokia 6600 and the Sony Ericsson P900/P908, untrusted MIDlets canaccess these APIs with User permission, the default being session. On theNokia 6600, the user can change the default setting for this function groupto Blanket (every invocation succeeds) or to disallow access altogether.4.7 Sample CodeIn this section we shall consider a small peer-to-peer application thattransmits an image between two Bluetooth devices using the Serial Portprofile over RFCOMM.

First we consider a MIDlet that offers a serviceto receive and display an image. The classes making up the BT DemoServer MIDlet are depicted in Figure 4.7.BTDemoServerImageCanvasFigure 4.7 A UML class diagram of the BT Demo Server MIDlet.The BTDemoServer code is listed below.importimportimportimportimportpublicjavax.microedition.midlet.*;javax.microedition.lcdui.*;javax.microedition.io.*;javax.bluetooth.*;java.io.*;class BTDemoServer extends MIDlet implements CommandListener,Runnable {private static final int IMAGE_SIZE = 11222;private ImageCanvas canvas;SAMPLE CODEprivateprivateprivateprivateprivate231Display display;Form displayForm;StringItem status = new StringItem("status: ", "Off");Command exitCommand = new Command("Exit", Command.EXIT, 1);Command startCommand = new Command("Start", Command.SCREEN,1);private Command stopCommand = new Command("Stop", Command.SCREEN, 1);private Command clearCommand = new Command("Clear", Command.SCREEN,1);privateprivateprivateprivateprivatefinal String uuid = "00112233445566778899AABBCCDDEEFF";LocalDevice device;byte[] data;boolean running = false;StreamConnection conn;public BTDemoServer() {data = new byte[IMAGE_SIZE];display = Display.getDisplay(this);}public void commandAction(Command c, Displayable d) {if (c == exitCommand) {destroyApp(true);notifyDestroyed();} else if (c == startCommand) {running = true;startServer();displayForm.removeCommand(startCommand);displayForm.removeCommand(exitCommand);displayForm.addCommand(stopCommand);status.setText("listening");} else if (c == stopCommand) {running = false;displayForm.addCommand(exitCommand);displayForm.addCommand(startCommand);displayForm.removeCommand(stopCommand);status.setText("Off");} else if (c == clearCommand) {display.setCurrent(displayForm);canvas.removeCommand(clearCommand);canvas.setCommandListener(null);canvas = null;}}public void startApp() {displayForm = new Form("Bluetooth Server");displayForm.setCommandListener(this);displayForm.addCommand(exitCommand);displayForm.addCommand(startCommand);display.setCurrent(displayForm);displayForm.append(status);}public void startServer() {try {device = LocalDevice.getLocalDevice();232JAVA APIs FOR BLUETOOTH WIRELESS TECHNOLOGYdevice.setDiscoverable(DiscoveryAgent.GIAC);Thread btServer = new Thread(this);btServer.start();} catch(BluetoothStateException bse) {status.setText("BSException: " + bse.toString());}}public void run() {try {StreamConnectionNotifier notifier =(StreamConnectionNotifier)Connector.open("btspp://localhost:"+ uuid + ";name=serialconn");ServiceRecord record = device.getRecord(notifier);record.setDeviceServiceClasses(0x40000);//SERVICE_RENDERINGwhile (running) {conn = notifier.acceptAndOpen();//record is saved to the SDDB on this callDataInputStream input = conn.openDataInputStream();input.readFully(data);input.close();DataOutputStream output = conn.openDataOutputStream();output.writeInt(-1);output.flush();output.close();conn.close();conn = null;Image image = Image.createImage(data, 0, IMAGE_SIZE);canvas = new ImageCanvas(image);canvas.addCommand(clearCommand);canvas.setCommandListener(this);display.setCurrent(canvas);}} catch(IOException ioe) {status.setText("IOException " + ioe.toString());} catch(Exception e) {status.setText("Exception: " + e.toString());}}public void destroyApp(boolean unconditionally) {try{if(conn != null)conn.close();}catch(IOException ioe){status.setText("IOException: " + ioe.toString());}}public void pauseApp() {}}SAMPLE CODE233<<Interface>>javax.bluetooth.DiscoveryListenerDeviceDiscovererBTDemoClientImageCanvasServiceDiscovererBluetoothUIFigure 4.8 A UML class diagram of the BT Demo Client MIDlet.Here we use a specific UUID of 00112233445566778899AABBCCDDEEFF to uniquely represent our service.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6358
Авторов
на СтудИзбе
311
Средний доход
с одного платного файла
Обучение Подробнее