This is my first project with bluecove and I am having problems before I even start!
Here is my code:
import java.io.IOException;
import java.util.ArrayList;
import bluecove;
/**
* Class that discovers all bluetooth devices in the neighbourhood and
displays their name and bluetooth address.
*/
public class BluetoothDeviceDiscovery implements DiscoveryListener {
// object used for waiting
private static Object lock = new Object();
// vector containing the devices discovered
public static ArrayList<RemoteDevice> devices;
public BluetoothDeviceDiscovery() {
devices = new ArrayList<RemoteDevice>();
}
// main method of the application
public static void main(String[] args) throws IOException {
//create an instance of this class
BluetoothDeviceDiscovery bluetoothDeviceDiscovery=new
BluetoothDeviceDiscovery();
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println("Address: " + localDevice.getBluetoothAddress());
System.out.println("Name: " + localDevice.getFriendlyName());
//find devices
DiscoveryAgent agent = localDevice.getDiscoveryAgent();
System.out.println("Starting device inquiry…");
agent.startInquiry(DiscoveryAgent.GIAC, bluetoothDeviceDiscovery);
try {
synchronized(lock) {
lock.wait();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Device Inquiry Completed. ");
//print all devices in devices
int deviceCount=devices.size();
System.out.println(deviceCount);
if(deviceCount <= 0) {
System.out.println("No Devices Found .");
} else {
//print bluetooth device addresses and names in the format [ No. address (name) ]
System.out.println("Bluetooth Devices:" );
for (int i = 0; i < deviceCount; i++) {
RemoteDevice remoteDevice=(RemoteDevice)devices.get(i);
System.out.println(i +". "+remoteDevice.getBluetoothAddress() );
//("+remoteDevice.getFriendlyName(true)+")");
}
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod)
{
System.out.println("Device discovered: "+btDevice.getBluetoothAddress());
//add the device to the vector
if(!devices.contains(btDevice))
{
devices.add(btDevice);
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
}
public void serviceSearchCompleted(int transID, int respCode) {
}
public void inquiryCompleted(int discType)
{
synchronized(lock){
lock.notify();
}
switch (discType)
{
case DiscoveryListener.INQUIRY_COMPLETED :
System.out.println("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
System.out.println("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
System.out.println("INQUIRY_ERROR");
break;
default :
System.out.println("Unknown Response Code");
break;
}
}
}
I am getting an error on line 3 (surprise, surprise) telling me that a ';' was expected.
I know the real reason I am getting an error is that I did not import bluecove correctly.
I downloaded the bluecove jar, renamed it and added the file to my classpath thinking that I could now import and use bluecove in my java projects.
Did I setup/import bluecove the wrong way? How do I actually import bluecove so I can use bluetooth in my project?
The first two import statements inform Java about the full package paths for the IOException and ArrayList classes that you are referencing in your code.
Once you start using bluecove classes in your code, you will need to add one or more import statements telling Java about the full package paths of those classes.
Just in case some impatient people come here for a quick copy&paste, here is my list of imports:
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
Related
The below code(not mine) is supposed to check the connection status of a zookeeper by using the znode_exists() method. I want to use it at a producerAPI before a message publish. But i am getting an error at defining the ZooKeeperConnection object. I have added the possible classes and libraries.
import java.io.IOException;
//import org.apache.zookeeper.*; adding this doesn't help
import org.apache.zookeeper.ZooKeeperMain;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;
public class ZKExists {
private static ZooKeeper zk;
private static ZooKeeperConnection conn; // Object cannot be resolve to a type
// Method to check existence of znode and its status, if znode is available.
public static Stat znode_exists(String path) throws
KeeperException,InterruptedException {
return zk.exists(path, true);
}
public static void main(String[] args) throws InterruptedException,KeeperException {
String path = "/Znode_path"; // Assign znode to the specified path
try {
ZooKeeperConnection conn = new ZooKeeperConnection();
zk = conn.connect("localhost");
Stat stat = znode_exists(path); // Stat checks the path of the znode
if(stat != null) {
System.out.println("Node exists and the node version is " +
stat.getVersion());
} else {
System.out.println("Node does not exists");
}
} catch(Exception e) {
System.out.println(e.getMessage()); // Catches error messages
}
}
}
Which library am i missing to make the object valid ?
I am new to scala. I am trying to import contacts from gmail in to my application.I can create sample application in java using Eclipse by following link https://developers.google.com/google-apps/contacts/v2/developers_guide_java?csw=1#retrieving_without_query
I can Import the contacts in My java application.And It works fine. My java code is
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.model.gd.Email;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
/**
* This is a test template
*/
public class Contacts {
public static void main(String[] args) {
try {
// Create a new Contacts service
System.out.println("hiiii"+args[0]);
ContactsService myService = new ContactsService("My Application");
myService.setUserCredentials(args[0],args[1]);
// Get a list of all entries
URL metafeedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+args[0]+"#gmail.com/base");
System.out.println("Getting Contacts entries...\n");
ContactFeed resultFeed = myService.getFeed(metafeedUrl, ContactFeed.class);
List<ContactEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
ContactEntry entry = entries.get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
System.out.println("\t" + entry.getEmailAddresses());
for(com.google.gdata.data.extensions.Email emi:entry.getEmailAddresses())
System.out.println(emi.getAddress());
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
System.out.println("Authentication failed");
}
catch(MalformedURLException e) {
e.printStackTrace();
System.out.println("url");
}
catch(ServiceException e) {
e.printStackTrace();
System.out.println("Service exc");
}
catch(IOException e) {
e.printStackTrace();
System.out.println("IO exception");
}
}
}
I tried to use same library functions for My Scala but it doesn't work. My Scala code is
import com.google.gdata.client.contacts.ContactsService
import com.google.gdata.data.contacts.ContactEntry
import com.google.gdata.data.contacts.ContactFeed
import com.google.gdata.util.ServiceException
import com.google.gdata.util.AuthenticationException
import java.io.IOException
import java.net.URL
import java.net.MalformedURLException
object Contacts {
class Test
{
def main(args:Array[String])
{
println("hiii")
try {
// Create a new Contacts service
//ContactsService myService = new ContactsService("My Application");
//myService.setUserCredentials(args[0],args[1]);
val myService= new ContactsService("My App")
myService.setUserCredentials("MyemailId","password")
val metafeedUrl = new URL("http://www.google.com/m8/feeds/contacts/"+"MyemailId"+"#gmail.com/base")
val resultFeed = myService.getFeed(metafeedUrl, classOf[ContactFeed])
//List<ContactEntry> entries = resultFeed.getEntries();
val entries = resultFeed.getEntries();
for(i <-0 to entries.size())
{
var entry=entries.get(i)
println(entry.getTitle().getPlainText())
}
}
catch{
case e:AuthenticationException=>{
e.printStackTrace();
}
case e:MalformedURLException=>{
e.printStackTrace();
}
case e:ServiceException=>{
e.printStackTrace();
}
case e:IOException=>
{
e.printStackTrace();
}
}
}
}
}
But it does not works. Can I use java library in Scala?
The problem that's causing your error, is that the object Contacts does not have a main method. Instead, it contains an inner class called Test which has a main method. I don't believe that is what you want (in Scala, object methods are the equivalent of Java static methods), so the main method should be moved out into Contacts, and the inner class deleted.
Also, for(i <-0 to entries.size()) is probably a mistake. This is roughly equivalent to for(int i=0; i<=entries.size(); i++) (notice the <=). You probably want for(i <-0 until entries.size()).
While you're there, you can kill the try..catch blocks if you like, as Scala doesn't use checked exceptions. If you import scala.collection.JavaConversions._, then you can use for (entry <- entries), which may be less error prone.
If it still doesn't work (or when posting future questions), provide as much info as you can (error messages, warnings, etc.), as it makes it far more likely that someone will be able to help.
I coded in java on ubuntu 11.10
Laptop webcam is running correctly and locate it /dev/v4l/.
Skype application can use webcam and run.
I installed JMF but i couldn't add environment variables.`
Vector deviceList = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceList.toString());
if(!deviceList.isEmpty()){
System.out.println("1");
device = (CaptureDeviceInfo) deviceList.firstElement();
}
device = (CaptureDeviceInfo) deviceList.firstElement();
ml = device.getLocator();
I want to just a capture a image in java.
What should i do solving the problem or use instead of JMF?
Before calling CaptureDeviceManager.getDeviceList(), the available devices must be loaded into the memory first.
You can do it manually by running JMFRegistry after installing JMF.
or do it programmatically with the help of the extension library FMJ (Free Media in Java). Here is the code:
import java.lang.reflect.Field;
import java.util.Vector;
import javax.media.*;
import javax.media.format.RGBFormat;
import net.sf.fmj.media.cdp.GlobalCaptureDevicePlugger;
public class FMJSandbox {
static {
System.setProperty("java.library.path", "D:/fmj-sf/native/win32-x86/");
try {
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
GlobalCaptureDevicePlugger.addCaptureDevices();
Vector deviceInfo = CaptureDeviceManager.getDeviceList(new RGBFormat());
System.out.println(deviceInfo.size());
for (Object obj : deviceInfo ) {
System.out.println(obj);
}
}
}
I was wondering if it is possible to check whether there is an instance of an object(my gui) open in Java and if so how I would be able to find it?
You can use following code if this question is for swing window like JFrame or JDialog,
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
if (win[i].getName().equals("YourWindowName"))
isOpen = true;
break;
}
For this ypu need to give name to your JFrame and if that matches with open windows it will set true and return.
I used RMI to solve the same problem. My application creates Registry and places a lock object there after start. If lock object is already there at that time then it sends message via RMI to existing application and terminates. The sent message triggers existing application to move its window on top. Here is the code
public static void main(String[] args) {
RmiManager rmiManager = new RmiManager();
rmiManager.createRmiRegistry();
if(rmiManager.isAlreadyRunning()) {
logger.error("Another application instance is running! Exit");
System.exit(0);
return;
}
rmiManager.registerApplication();
}
RmiManager.java which is actually responsible for all the stuff
package myapp;
import java.rmi.AccessException;
import java.rmi.AlreadyBoundException;
import java.io.File;
import java.io.IOException;
import java.rmi.registry.LocateRegistry;
import java.rmi.NotBoundException;
import java.rmi.registry.Registry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import org.apache.log4j.Logger;
public class RmiManager {
private static final String LOCK_OBJECT_NAME = "myapp";
private static final Logger logger = Logger.getLogger(RmiManager.class);
public void createRmiRegistry() {
try {
logger.debug("Creating RMI registry...");
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
logger.debug("RMI registry was created");
} catch (RemoteException e) {
logger.debug("RMI registry is already created");
}
}
public boolean isAlreadyRunning() {
try {
logger.debug("Checking if application is already running. Looking for RMI registry...");
Registry registry = LocateRegistry.getRegistry();
logger.debug("RMI registry obtained. Looking for RmiListener: " + LOCK_OBJECT_NAME + "...");
try {
IRmiListener rmiListener = (IRmiListener) registry.lookup(LOCK_OBJECT_NAME);
logger.debug("RmiListener got. Checking...");
boolean isAlreadyRunning = rmiListener.isAlreadyRunning();
logger.debug("IsAlreadyRunning result: " + isAlreadyRunning);
return isAlreadyRunning;
} catch (AccessException e) {
logger.error("Error accessing RMI registry!", e);
return false;
} catch (NotBoundException e) {
logger.debug("RMI listener wasn't found. There are no other application instances running");
return false;
}
} catch (RemoteException e) {
logger.error("RemoteException!", e);
return false;
}
}
public void registerApplication() {
try {
logger.debug("Registering application...");
RmiListenerImpl rmiListenerImpl = new RmiListenerImpl();
logger.debug("Exporting RmiListener object...");
IRmiListener rmiListener = (IRmiListener) UnicastRemoteObject.exportObject(rmiListenerImpl, Registry.REGISTRY_PORT);
logger.debug("RmiListener object was exported. Looking for RMI registry...");
Registry registry = LocateRegistry.getRegistry();
logger.debug("RMI registry found");
try {
logger.debug("Binding RmiListener to " + LOCK_OBJECT_NAME + "...");
registry.bind(LOCK_OBJECT_NAME, rmiListener);
logger.debug("RmiListener binding was done. Application registration complete.");
} catch (AccessException e) {
logger.error("AccessException!", e);
} catch (AlreadyBoundException e) {
logger.error("RmiListener object is already bind", e);
}
} catch (RemoteException e) {
logger.error("RemoteException!", e);
}
}
}
IRmiListener.java
package myapp;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IRmiListener extends Remote {
boolean isAlreadyRunning() throws RemoteException;
}
RmiListenerImpl.java
package myapp;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
public class RmiListenerImpl implements IRmiListener {
private static final Logger logger = Logger.getLogger( RmiListenerImpl.class );
#Override
public boolean isAlreadyRunning() throws RemoteException {
// here I notify my GUI class to pop up the window
return true;
}
}
It can be more simple I think.
Assuming that by "open UI objects" you mean Swing dialogs and frames, it is better to design the application in a way that would remove the need to look for open instances all together.
This can be achieved by providing a factory that would produce application dialogs and frames instead of using something like new JFrame. This factory would register the produced instances internally and would serve as a single point of reference for all "open UI objects".
Although, be careful when implementing such solution as every registered object would have one additional reference preventing GC from collecting the allocated memory as intended. Please used weak references (weak reference map) for caching. A good blog post about different kinds of Java references can be found here.
This way if you need to find an open UI object, simply request your factory to provide a list of open instances.
I'm trying to understand how to work with Skype using java (JSkype lib)
i use example (official site):
package testproj;
import net.lamot.java.jskype.general.AbstractMessenger;
import net.lamot.java.jskype.general.MessageListenerInterface;
import net.lamot.java.jskype.windows.Messenger;
import java.lang.Thread;
import java.lang.Exception;
import java.util.Date;
public class JSkype implements MessageListenerInterface {
private AbstractMessenger msgr = null;
public JSkype() {
msgr = new Messenger();
msgr.addListener(this);
msgr.initialize();
try {
Thread.sleep(5000);
msgr.sendMessage("MESSAGE echo123 test message");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new JSkype();
}
public void onMessageReceived(String str) {
System.out.println("RESULT: "+str);
}
}
after run, in console i have many information, but for me more intresting information, that I receive after send message:
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: MESSAGE 21129 STATUS SENDING
RESULT: CHAT #my.name/$echo123;9797238991f90d78 ACTIVITY_TIMESTAMP 1294574640
and now I'm trying to understand, how to determine the success of sending a message?
yep, we need parsind result string.. but what is a number 21129? 9797238991f90d78? how i can know this number before start parsing?