Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,854 members, 7,810,284 topics. Date: Saturday, 27 April 2024 at 05:27 AM

Bluemall => A Bluetooth Based Mobile Advert System Created In Java. - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Bluemall => A Bluetooth Based Mobile Advert System Created In Java. (1452 Views)

Problem With Bufferedinputstream Read Blocking Issue In Java / I Want To Develop A Software In Java To Calculate CGPA / How Do Io Create Ribbon Ui In Java (2) (3) (4)

(1) (Reply) (Go Down)

Bluemall => A Bluetooth Based Mobile Advert System Created In Java. by javaprince(m): 2:44pm On Apr 04, 2009
This program demonstrates the use of Bluetooth technology to send images in a Java Program. Just posting it here so that anyone that needs to work on bluetooth could learn from this.


/*
* BlueMall.java
* Bluetooth Application that starts a server, detects bluetooth devices in the area
* and automatically send image files to it
*/
package bluemall.server;

import bluemall.client.ClientDevice;
import de.avetana.bluetooth.connection.Connector;
import java.util.logging.*;
import java.util.*;
import java.net.URL;
import javax.bluetooth.*;
import javax.obex.*;
import javax.bluetooth.UUID;
import java.io.*;

/**
*
* @author temitope
*/
public class BlueMallServer {

private static Logger log = null;
final Object lock = new Object();
private Vector<ClientDevice> clientList = new Vector<ClientDevice>();
Vector<ClientDevice> newClientList = new Vector<ClientDevice>();
private Vector<String> services = new Vector<String>();
final long SLEEP_TIME = 5; //sleep interval in minutes
final int RUNS = 5; //after 5 runs reset/clear clientList

public BlueMallServer() {
initializeLog();
new DetectThread().start();
}

/**
* Initializes log
*/
private void initializeLog() {

log = Logger.getLogger("bluemall.server"wink;
//log.setLevel(Level.SEVERE);
// FileHandler fileHandler = new FileHandler();
// fileHandler.setFormatter(new SimpleFormatter());
}

public static void main(String args[]) {
new BlueMallServer();
}

/**
* @return the newClientList
*/
public Vector<ClientDevice> getClientDevice() {
return clientList;
}

private class DetectThread extends Thread implements DiscoveryListener {

LocalDevice localDevice = null;
int runs = 1;

@Override
public void run() {
boolean first = true;
while (true) {
if (++runs == RUNS) {
runs = 1;
log.info("Clearing Old List"wink;
clientList.clear();
}
try {
localDevice = LocalDevice.getLocalDevice();
if (first) {
log.info("Server Bluetooth Address: " + localDevice.getBluetoothAddress());
log.info("Server Bluetooth Name: " + localDevice.getFriendlyName());
first = false;
}
log.info("Begin searching for Devices, "wink;
searchDevices();
updateStatus();
log.info("Number of Devices Found: " + clientList.size());

//search for services
searchServices();

//send files to each service
sendFiles();
// try {
// synchronized (lock) {
// lock.wait();
// }
// } catch (Exception ex) {
// log.severe(ex.getMessage());
// }
Thread.sleep(SLEEP_TIME * 1000);
} catch (Exception ex) {
log.severe(ex.getMessage());
}
}
}

private synchronized boolean clientContainsDevice(ClientDevice clientDevice) {
boolean result = false;
String sourceAddress = null;
try {
sourceAddress = clientDevice.getBluetoothAddress();
for (ClientDevice cd : clientList) {
String eachAddress = cd.getBluetoothAddress();
if (eachAddress.equals(sourceAddress)) {
result = true;
}
}
} catch (Exception ex) {
log.info(ex.getMessage());
}
return result;
}

private void searchDevices() {
try {
DiscoveryAgent agent = localDevice.getDiscoveryAgent();

agent.startInquiry(DiscoveryAgent.GIAC, this);

try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}

} catch (Exception ex) {
log.severe(ex.getMessage());
}
}

private void searchServices() {
try {
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
int[] attrSet = new int[]{0x1101};
UUID uuidSet[] = new UUID[1];
uuidSet[0] = new UUID(0x1105);
services.clear();
for (ClientDevice remoteDevice : clientList) {
agent.searchServices(null, uuidSet, remoteDevice.getRemoteDevice(), this);
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
log.severe(ex.getMessage());
}
}

public void deviceDiscovered(RemoteDevice rmd, DeviceClass deviceClass) {
try {
//Construct Client devices
ClientDevice clientDevice = new ClientDevice(rmd.getBluetoothAddress());
clientDevice.setRemoteDevice(rmd);
clientDevice.setBluetoothName(rmd.getFriendlyName(true));
clientDevice.setCreatedDate(new Date());
clientDevice.setLastAdvert(null);
clientDevice.setNumberOfAdverts(0);
System.out.println(clientDevice.toString());
if (!clientContainsDevice(clientDevice)) {
clientList.addElement(clientDevice);
newClientList.addElement(clientDevice);

//search for service on device

}
} catch (Exception ex) {
log.severe(ex.getMessage());
}
}

private void sendFiles() {
for (String url : services) {
try {
sendFile(url);
} catch (Exception ex) {
log.severe(ex.getMessage());
continue;
}
}
}

private void sendFile(String url) throws Exception {
try {//send file
ClientSession clientSession = (ClientSession) Connector.open(url);
HeaderSet headerSet = clientSession.connect(null);
if (headerSet.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) {
log.severe("Failed to connect!!!"wink;
return;
}
log.info("Connected Successfully!!! to service " + url);
HeaderSet hsOperation = clientSession.createHeaderSet();
hsOperation.setHeader(HeaderSet.NAME, "notice.jpg"wink;

//hsOperation.setHeader(HeaderSet.TYPE, "image/jpeg"wink;
Operation putOperation = clientSession.put(hsOperation);
log.info("Begin file copying, "wink;

//Open file on local system
FileInputStream in = new FileInputStream(new ImageGenerator().getImageFile());
OutputStream out = putOperation.openOutputStream();

byte data[] = new byte[in.available()];
in.read(data);
in.close();
out.write(data);
out.flush();
out.close();

System.out.println("File Copied Successfully!!!"wink;
putOperation.close();
clientSession.disconnect(null);
clientSession.close();
} catch (BluetoothStateException bex) {
log.severe(bex.getMessage());
} catch (IOException ioex) {
log.severe(ioex.getMessage());
}
}

private void updateStatus() {
top:
for (ClientDevice oldList : clientList) {
oldList.setStatus(false);
for (ClientDevice newList : newClientList) {
if (oldList.getBluetoothAddress().equals(newList.getBluetoothAddress())) {
oldList.setStatus(false);
continue top;
}
}
}
log.info("Clearing New List, "wink;
newClientList.clear();
}

public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
if (servRecord != null && servRecord.length > 0) {
String url = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
if (url != null && !url.equals(""wink) {
services.addElement(url);
log.info("Service Discovered: " + url);
}
}
}

public void serviceSearchCompleted(int arg0, int arg1) {
synchronized (lock) {
lock.notify();
}
}

public void inquiryCompleted(int arg0) {
synchronized (lock) {
lock.notify();
}
}
}

/**
* ImageGenerator.java
* class to get Image using an algorithm
*
*/
private class ImageGenerator {
String baseName = "/bluemall/images/image";
int i = 1;
public File getImageFile() throws Exception {
URL url = BlueMallServer.class.getResource(baseName + i+".jpg"wink;
File imageFile = new File(url.toURI());

return imageFile;
}
}
}





/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bluemall.client;

import java.util.Date;
import java.util.logging.*;
import javax.bluetooth.RemoteDevice;

/**
*
* @author temitope
* @version 1.0
*/
public class ClientDevice {

private static Logger log = Logger.getLogger("bluemall.client"wink;

RemoteDevice remoteDevice = null;
String bluetoothAddress;
String bluetoothName;
Date createdDate;
int numberOfAdverts;
Date lastAdvert;
boolean status = true;


/**
*
* @param _bluetoothAddress
*/
public ClientDevice(String _bluetoothAddress) {
log.setLevel(Level.SEVERE);

log.info("Constructing a client device"wink;
this.bluetoothAddress = _bluetoothAddress;
}

/**
* @return the bluetoothAddress
*/
public String getBluetoothAddress() {
return bluetoothAddress;
}

/**
* @param bluetoothAddress the bluetoothAddress to set
*/
public void setBluetoothAddress(String bluetoothAddress) {
this.bluetoothAddress = bluetoothAddress;
}

/**
* @return the bluetoothName
*/
public String getBluetoothName() {
return bluetoothName;
}

/**
* @param bluetoothName the bluetoothName to set
*/
public void setBluetoothName(String bluetoothName) {
this.bluetoothName = bluetoothName;
}

/**
* @return the createdDate
*/
public Date getCreatedDate() {
return createdDate;
}

/**
* @param createdDate the createdDate to set
*/
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}

/**
* @return the numberOfAdverts
*/
public int getNumberOfAdverts() {
return numberOfAdverts;
}

/**
* @param numberOfAdverts the numberOfAdverts to set
*/
public void setNumberOfAdverts(int numberOfAdverts) {
this.numberOfAdverts = numberOfAdverts;
}

/**
* @return the lastAdvert
*/
public Date getLastAdvert() {
return lastAdvert;
}

/**
* @param lastAdvert the lastAdvert to set
*/
public void setLastAdvert(Date lastAdvert) {
this.lastAdvert = lastAdvert;
}

@Override
public String toString() {
String message = "";
message += "Client Device Address: " + this.getBluetoothAddress();
message += "\nClient Friendly Name: " + this.getBluetoothName();
message += "\nDate Created: " + this.getCreatedDate();
message+= "\nStatus : " + this.isStatus();

return message;
}

/**
* @return the status
*/
public boolean isStatus() {
return status;
}

/**
* @param status the status to set
*/
public void setStatus(boolean status) {
this.status = status;
}

/**
* @return the remoteDevice
*/
public RemoteDevice getRemoteDevice() {
return remoteDevice;
}

/**
* @param remoteDevice the remoteDevice to set
*/
public void setRemoteDevice(RemoteDevice remoteDevice) {
this.remoteDevice = remoteDevice;
}
}
Re: Bluemall => A Bluetooth Based Mobile Advert System Created In Java. by candylips(m): 9:33am On Apr 06, 2009
Which java api are u using for this ?
Re: Bluemall => A Bluetooth Based Mobile Advert System Created In Java. by ade2kay(m): 3:46pm On Apr 06, 2009
javaprince:


import bluemall.client.ClientDevice;
import de.avetana.bluetooth.connection.Connector;

and the java bluetooth APIs
Re: Bluemall => A Bluetooth Based Mobile Advert System Created In Java. by javaprince(m): 1:27pm On Apr 08, 2009
@all
Sorry for going for so long.

I just intended to demostrate how to use a Java Program to interact with your bluetooth device on PC system and hence use ut to send files using the OBEX (Object Exchange) Protocol and the JSR 82 bluetooth specification.

The Java library to use is either Bluecove(from google) or Avetana Bluetooth library. Do a simple Google search you should be able to get them at first hit. They also come with detailed javadocs(at least the Bluecove).

JAND(Java Nigerian Developers) www.naiadukes.net/jand

(1) (Reply)

How To Maximize Search Engine Rankings? / How To Run Localhost Or Web Server On Your Android Phone / Need Help In IT Placement In Lagos For 2017

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 28
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.