mac address problem - java

I want to get the mac address of another computer in lan how can I do it? I am using JPCAP
private void getPackage(JpcapCaptor captor)
{
try{
IPPacket ip = (IPPacket)captor.getPacket();
for(int a =0 ; a <found.size(); a++ )
{
if(ip.dst_ip.equals(found.get(a)))
check = true;
}
if(!check)
{
if(ip.dst_ip.isSiteLocalAddress())
{
host = ip.dst_ip.getHostName();
System.out.println("destination ip : " + ip.dst_ip + " " + ip.dst_ip.getHostName());
System.out.println("Source ip : " + ip.src_ip + " " + ip.src_ip.getHostName());
found.addElement(ip.dst_ip);
}
}
check = false;
}catch(Exception ex)
{
//Sys.alert("Error" ,"lobby exeption :" + ex);
//wegens null reverence exeption
}
}
this code just get the IP address but I want mac address too

http://netresearch.ics.uci.edu/kfujii/Jpcap/doc/javadoc/jpcap/packet/ARPPacket.html
You need the method:
public java.lang.Object getSenderHardwareAddress()
package jpcapExample;
import jpcap.*;
import jpcap.packet.*;
class PacketPrinter implements PacketReceiver {
public void receivePacket(Packet packet) {
if (packet instanceof ARPPacket){
ARPPacket arpp = (ARPPacket) packet;
Object str = arpp.getSenderHardwareAddress();
System.out.println("got arp from: " + str.toString());
}
System.out.println(packet);
}
}
---------------------[ different file ]-------------
try {
JpcapCaptor eth0=
JpcapCaptor.
openDevice(devices[eth0idx], 65535, false, 20000);
while (true){
eth0.processPacket(1233,new PacketPrinter());
}
} catch (IOException io){
io.printStackTrace();
}

Related

How to get IPAddress using InetAddress in Android [duplicate]

This question already has answers here:
How do I fix a compilation error for unhandled exception on call to Thread.sleep()?
(2 answers)
Closed 5 years ago.
I'm having difficulty using InetAddress in Java for my Android project. I included the InetAddress library, however it never works.
The code is the follow:
InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
However all time show me:
Description Resource Path Location Type
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor LauncherActivity.java /src/my/app/client line 25 Java Problem
I included the library:
import java.net.InetAddress;
What must I do to use InetAddress in my Android Project?
The class of my project is:
public class LauncherActivity extends Activity
{
/** Called when the activity is first created. */
Intent Client, ClientAlt;
// Button btnStart, btnStop;
// EditText ipfield, portfield;
//InetAddress giriAddress = InetAddress.getByName("www.girionjava.com");
//private InetAddress giriAddress;
private InetAddress giriAddress;
public LauncherActivity()
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
private String myIp = "MYIP"; // Put your IP in these quotes.
private int myPort = PORT; // Put your port there, notice that there are no quotes here.
#Override
public void onStart()
{
super.onStart();
onResume();
}
#Override
public void onResume()
{
super.onResume();
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
moveTaskToBack(true);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
Client = new Intent(this, Client.class);
Client.setAction(LauncherActivity.class.getName());
getConfig();
Client.putExtra("IP", myIp);
Client.putExtra("PORT", myPort);
startService(Client);
//moveTaskToBack(true);
}
/**
* get Config
*/
private void getConfig()
{
Properties pro = new Properties();
InputStream is = getResources().openRawResource(R.raw.config);
try
{
pro.load(is);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myIp = pro.getProperty("host");
myPort = Integer.valueOf(pro.getProperty("prot"));
System.out.println(myIp);
System.out.println(myPort);
}
}
The error's i get.
Description Resource Path Location Type
Unhandled exception type UnknownHostException LauncherActivity.java /Androrat/src/my/app/client line 31 Java Problem
Picture:
MY VERSION OF JAVA IS JAVA SE 1.6
I propose two alternatives:
If the IP of the given host is mandatory for your application to work properly, you could get it into the constructor and re-throw the exception as a configuration error:
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
{
try {
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
catch (UnknownHostException e)
{
throw new ServiceConfigurationError(e.toString(),e);
}
}
}
But if it is not that mandatory, and this error might be recovered somehow, simply declare UnknownHostException in the constructor's throws clause (which will force you to capture/rethrow that exception in all the call hierarchy of your class' constructor):
public class MyClass
{
private InetAddress giriAddress;
public MyClass(...)
throws UnknownHostException
{
this.giriAddress=InetAddress.getByName("www.girionjava.com");
}
}
This is my simple method using my android application.
private static int timeout = 500;
private static int isIpAddressString(String tstr, byte[] ipbytes)
{
final String str = tstr;
boolean isIpAddress = true;
StringTokenizer st = new StringTokenizer(str, ".");
int idx = 0;
if(st.countTokens() == 4)
{
String tmpStr = null;
byte[] ipBytes = new byte[4];
while(st.hasMoreTokens())
{
tmpStr = st.nextToken();
for (char c: tmpStr.toCharArray()) {
if(Character.isDigit(c)) continue;
else
{
//if(c != '.')
{
isIpAddress = false;
break;
}
}
}
if(!isIpAddress) break;
ipBytes[idx] = (byte)(Integer.valueOf(tmpStr.trim()).intValue());
idx++;
}
System.arraycopy(ipBytes, 0, ipbytes, 0, ipbytes.length);
}
return idx;
}
public static boolean canResolveThisUrlString(final String TAG, String urlStr)
{
String resolveUrl = urlStr;
boolean isResolved = false;
java.net.InetAddress inetaddr = null;
try
{
//java.net.InetAddress addr = java.net.InetAddress.getByName(resolveUrl);
byte[] ipbytes = new byte[4];
if(isIpAddressString(urlStr, ipbytes) == 4)
{
inetaddr = java.net.InetAddress.getByAddress(ipbytes);
}
else
{
String host = null;
if(resolveUrl.startsWith("http") ||resolveUrl.startsWith("https") )
{
URL url = new URL(resolveUrl);
host = url.getHost();
}
else
host = resolveUrl;
inetaddr = java.net.InetAddress.getByName(host);
}
//isResolved = addr.isReachable(SettingVariables.DEFAULT_CONNECTION_TIMEOUT);
isResolved = inetaddr.isReachable(timeout);
//isResolved = true;
}
catch(java.net.UnknownHostException ue)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, ue);
ue.printStackTrace();
isResolved = false;
}
catch(Exception e)
{
//com.skcc.alopex.v2.blaze.util.BlazeLog.printStackTrace(TAG, e);
e.printStackTrace();
isResolved = false;
}
//System.out.println(isResolved + "::::::::" + inetaddr.toString());
return isResolved;
}
You can test it with
public static void main(String[] args)
{
String urlString = "https://www.google.com";
String urlString1 = "www.google.com";
String urlString2 = "https://www.google.co.kr/search?q=InetAddress+create&rlz=1C1NHXL_koKR690KR690&oq=InetAddress+create&aqs=chrome..69i57j0l5.5732j0j8&sourceid=chrome&ie=UTF-8";
String urlString3 = "127.0.0.1";
//URL url = null;
try {
boolean canResolved = canResolveThisUrlString(null, urlString);
System.out.println("resolved " + canResolved + " : url [" + urlString + "]");
canResolved = canResolveThisUrlString(null, urlString1);
System.out.println("resolved " + canResolved + " : url [" + urlString1 + "]");
canResolved = canResolveThisUrlString(null, urlString2);
System.out.println("resolved " + canResolved + " : url [" + urlString2 + "]");
canResolved = canResolveThisUrlString(null, urlString3);
System.out.println("resolved " + canResolved + " : url [" + urlString3 + "]");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you've got a UnknownHostException from your app when the url you've requested can't be resolved by whatever dns servers.
This case, you can not get any host name with ip address like 'www.girionjava.com' host in the internet world.

Google Contact API (No Authentication Header Information Error)

I am new to Google Contact Api. i am trying to retrieve all my contacts using Google Contact API. For this I used Oauth authentication and Google Contact API.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters.OAuthType;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;
public class GoogleContactsAccess{
/* This method will authenticate the user credentials passed to it and returns an instance of ContactService class.*/
public ContactsService authenticateId(){
GoogleOAuthParameters oAuthParameters = null;
ContactsService contactService = null;
try{
contactService = new ContactsService("API Project");
oAuthParameters = new GoogleOAuthParameters();
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
oAuthParameters.setScope("https://www.google.com/m8/feeds");
oAuthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oAuthParameters.addCustomBaseParameter("xoauth_requestor_id", "my ID#gmail.com");
contactService.setOAuthCredentials(oAuthParameters,new OAuthHmacSha1Signer());
contactService.getRequestFactory().setHeader("GData-Version", "3.0");
}catch(Exception e){
e.printStackTrace();
}
return contactService;
}
/* This method will print details of all the contacts available in that particular Google account. */
public void printAllContacts(ContactsService myService)throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json'");
// The query that will retrieve all contacts
Query myQuery = new Query(feedUrl);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
// Print the results
System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("\t\t" + fullNameToDisplay);
} else {
System.out.println("\t\t (no full name found)");
}
if (name.hasNamePrefix()) {
System.out.println("\t\t" + name.getNamePrefix().getValue());
} else {
System.out.println("\t\t (no name prefix found)");
}
if (name.hasGivenName()) {
String givenNameToDisplay = name.getGivenName().getValue();
if (name.getGivenName().hasYomi()) {
givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
}
System.out.println("\t\t" + givenNameToDisplay);
} else {
System.out.println("\t\t (no given name found)");
}
if (name.hasAdditionalName()) {
String additionalNameToDisplay = name.getAdditionalName().getValue();
if (name.getAdditionalName().hasYomi()) {
additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
}
System.out.println("\t\t" + additionalNameToDisplay);
} else {
System.out.println("\t\t (no additional name found)");
}
if (name.hasFamilyName()) {
String familyNameToDisplay = name.getFamilyName().getValue();
if (name.getFamilyName().hasYomi()) {
familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
}
System.out.println("\t\t" + familyNameToDisplay);
} else {
System.out.println("\t\t (no family name found)");
}
if (name.hasNameSuffix()) {
System.out.println("\t\t" + name.getNameSuffix().getValue());
} else {
System.out.println("\t\t (no name suffix found)");
}
} else {
System.out.println("\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print(" " + email.getAddress());
if (email.getRel() != null) {
System.out.print(" rel:" + email.getRel());
}
if (email.getLabel() != null) {
System.out.print(" label:" + email.getLabel());
}
if (email.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("IM addresses:");
for (Im im : entry.getImAddresses()) {
System.out.print(" " + im.getAddress());
if (im.getLabel() != null) {
System.out.print(" label:" + im.getLabel());
}
if (im.getRel() != null) {
System.out.print(" rel:" + im.getRel());
}
if (im.getProtocol() != null) {
System.out.print(" protocol:" + im.getProtocol());
}
if (im.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("Groups:");
for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
String groupHref = group.getHref();
System.out.println(" Id: " + groupHref);
}
System.out.println("Extended Properties:");
for (ExtendedProperty property : entry.getExtendedProperties()) {
if (property.getValue() != null) {
System.out.println(" " + property.getName() + "(value) = " +
property.getValue());
} else if (property.getXmlBlob() != null) {
System.out.println(" " + property.getName() + "(xmlBlob)= " +
property.getXmlBlob().getBlob());
}
}
Link photoLink = entry.getContactPhotoLink();
String photoLinkHref = photoLink.getHref();
System.out.println("Photo Link: " + photoLinkHref);
if (photoLink.getEtag() != null) {
System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
}
System.out.println("Contact's ETag: " + entry.getEtag());
}
}
public static void main(String args[]){
try {
GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();
ContactsService contactSrv = googleContactsAccess.authenticateId();
googleContactsAccess.printAllContacts(contactSrv);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
i tried the above code. i am getting the below exception
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:1077)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676)
at com.google.gdata.client.Service.getFeed(Service.java:1034)
at com.cohere.getcontacts.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:59)
at com.cohere.getcontacts.GoogleContactsAccess.main(GoogleContactsAccess.java:197)
so any one help me to resolve the problem thanks in advance
It looks like you are using ConsumerKey as both key and secret in your code :
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
You need to use the correct ConsumerSecret of your app

Get variable from one Java class into GUI form Java class JLabel

I want to get device connected: true JLabel in DisplayForm.java GUI if I press the connectBtn in DisplayForm.java GUI, but I can't get the variable String connected = "true"; from ArduinoDisplay.java to DisplayForm.java connectedDevice JLabel when I press connectBtn in DisplayForm.java.
Part of ArduinoDisplay.java
String connected = "";
public void initialize() {
if (portId == null) {
System.out.println("Could not find COM port.");
connected = "False";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
return;
} else if( portId != null) {
connected = "True";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
} else {
connected = "False";
System.out.println("CONNECTED: " + connected + " PORT: " + devCom);
}
}
public static void main(String[] args) throws Exception {
ArduinoDisplay main = new ArduinoDisplay();
main.initialize();
// Start GUI
DisplayForm gui = new DisplayForm();
gui.setVisible(true);
}
Part of the DisplayForm.java
private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
ArduinoDisplay ad = new ArduinoDisplay();
String devCon = ad.connected;
deviceConnected.setText(devCon);
}
If more code is needed, let me know, thank you
Put the connected variable outside of any method and do not allow direct access to it (use a getter method)
public class ArduinoDisplay {
private String connected = "false":
public String getConnected (){
return this.connected;
}
....
}
and get it like this:
private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
ArduinoDisplay ad = new ArduinoDisplay();
String devCon = ad.getConnected();
deviceConnected.setText(devCon);
}
Side Note: try to use boolean instead of a String. Or Enum's if you need several states. It saves you time and eliminates developer typo's

How to restore a MySQL database backup using Java

I was able to create a backup of my current mysql database as .SQL file using the mysqldump.exe with the help of the following java code.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
Now I want to restore this same .SQL Backup file to mysql database using java code similar to above on the event of a button clicked.
Thanks a lot :)
So now I tried this ;
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr < C:\\SCM Files\\SQL Backup\\RR.sql");
Still it didn't work :/
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"mysql", "--user=" + dbUserName, "--password=" + dbPassword, dbName,"-e", " source "+source};
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup restored successfully");
return true;
}
} else {
System.out.println("Could not restore the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
source example : "E:\\My Backup\\Test\\file.sql"
Runtime.getRuntime().exec("mysql -u username -ppassword database_name FILE.sql")
This statement will regenerate database from the file
You have to use java swings where you can design forms. Here is some code which can do that.
import javax.swing.JFrame;
public final class RestoreMySQLDatabase extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
RestoreMySQLDatabase restoreMySQL = new RestoreMySQLDatabase();
restoreMySQL.setTitle("Restore mysql database");
javax.swing.JButton butRestore = new javax.swing.JButton("Restore");
butRestore.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
try{
Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr -r\"C:\\SCM Files\\SQL Backup\\RR.sql");
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Successfully restored");
}catch(java.lang.Exception e){
javax.swing.JOptionPane.showMessageDialog((javax.swing.JButton)event.getSource(), "Not able to restore");
}
}
});
}
}
I tried this code and works as perfect!
String[] restoreCmd = new String[]{"mysql ", "--user=" + DB.DB_USERNAME, "--password=" + DB.DB_PASSWORD, "-e", "source " + pathToFile};
try {
Process runtimeProcess = Runtime.getRuntime().exec(restoreCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Done");
} else {
System.out.println("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
You should try DbUnit for backup and restore of database.Here is the demo code for that:
try {
Class.forName(DBDRIVER);
Connection jdbcConnection = DriverManager.getConnection(DBURL, DBUSERNAME, DBPASSWORD);
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new MySqlDataTypeFactory());
//////// Database backup
ITableFilter filter = new DatabaseSequenceFilter(connection);
IDataSet dataset = new FilteredDataSet(filter, connection.createDataSet());
ExcludeTableFilter excludeFilter = new ExcludeTableFilter();
excludeFilter.excludeTable("DATABASECHANGELOG*");
IDataSet excludedataset = new FilteredDataSet(excludeFilter, dataset);
FlatXmlDataSet.write(excludedataset, new FileOutputStream(backupfilename));
System.out.println("\n Complete backup successful.");
//////// Database backup
//////// Database restore
IDataSetProducer producer = new FlatXmlProducer(new InputSource(restoreFileName));
IDataSet dataSet = new StreamingDataSet(producer);
TransactionOperation operation = new TransactionOperation(DatabaseOperation.INSERT);
operation.execute(connection, dataSet);
//////// Database restore
} catch (DatabaseUnitException e) {
e.printStackTrace();
flag = false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Use the same dump to import like this.
Process runProcess = Runtime.getRuntime().exec("C:\\SCM Files\\SQL Backup\\mysqldump.exe -uroot -p123 rr database_name < "C:\\SCM Files\\SQL Backup\\RR.sql");
For restore use the executeCmd in the form m.Torkashvand provided (array of strings). A working example on how to use these commands from JSP code can be found here
public static void mysqlExport(String host, String port, String user, String password, String dbname, String table, String folder, String query) {
System.out.println("------ Exporting "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysqldump --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " --where=\"" + query + "\" > " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(Arrays.asList("mysqldump", "--host="+host, "--port="+port, "--user="+user, "--password="+password, dbname, table, "--where="+query), folder + table + ".sql");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void mysqlImport(String host, String port, String user, String password, String dbname, String table, String folder) {
System.out.println("------ Importing "+dbname+"."+table+" at "+folder+"---------------------------");
try {
String command = "mysql --host=" + host + " --port=" + port + " --user=" + user + " --password=" + password + " " + dbname + " " + table + " < " + folder + table + ".sql";
System.out.println(command);
int returnValue = executeCommand(new String[]{"mysql", "--host="+host, "--port="+port, "--user=" + user, "--password=" + password, dbname, "-e", "source " + folder + table + ".sql"});
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static int executeCommand(String[] commands) throws IOException
{
System.out.println(commands.toString());
Process process = Runtime.getRuntime().exec(commands);
return dumpProcess(process);
}
public static int executeCommand(List<String> commands, String folder) throws IOException
{
ProcessBuilder builder = new ProcessBuilder(commands);
System.out.println(builder.command());
builder.redirectOutput(new File(folder));
Process process = builder.start();
return dumpProcess(process);
}
public static int dumpProcess(Process process) throws IOException
{
int returnValue = -1;
try {
String s = null;
process.waitFor();
returnValue = process.exitValue();
if (returnValue == 0) {
System.out.println("Command successful !!");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
System.out.println("Command failed. Exist Status code = "+returnValue);
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
This is working code
public class Recover {
final static String filepath = "/home/shubhampanchal/Downloads/backup/configuration_files.sql";
public static void main(String[] args) throws Exception {
try {
String[] restoreCmd = new String[]{"mysql", "-uroot", "-p1", "Student", "-e", "source " + filepath};
Runtime rt =Runtime.getRuntime();
rt.exec(restoreCmd);
System.out.println("Restored successfully!");
} catch(Exception e) {
e.printStackTrace();
}
}
}

Bluecove: SERVICE_SEARCH_DEVICE_NOT_REACHABLE issue

I try to connect to a custom Bluetooth device using BlueCove. I can pair the device, but when I try to search for services I always get SERVICE_SEARCH_DEVICE_NOT_REACHABLE in serviceSearchCompleted() and no services are discovered. If I try the same thing outside Java (in Windows), the PC bluetooth device discovers and can connect (using COM21, COM22, ...) to the SPP service on my device.
What am I doing wrong?
I also tried to do the service search after the device discovery is ended. Same issue.
Please find below my code.
Many thanks in advance for any idea on how to solve this,
Adrian.
public class Test {
private static Logger LOG = Logger.getLogger(Test.class.getName());
private static final String NAME = "XXXX";
private static final String PIN = "1234";
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003), new UUID(0x1101)};
private LocalDevice localDevice;
private DiscoveryAgent discoveryAgent;
private DiscoveryListener discoveryListener = new GDiscoveryListener();
private Map<Integer, RemoteDevice> searchForServices = new HashMap<Integer, RemoteDevice>();
private Collection<ServiceRecord> servicesDiscovered = new HashSet<ServiceRecord>();
private Object lock = new Object();
private CountDownLatch waitForDevices;
protected void connect() {
try {
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
LOG.info("Local Device: " + localDevice.getFriendlyName()
+ "(" + localDevice.getBluetoothAddress() + ")");
discoveryAgent = localDevice.getDiscoveryAgent();
LOG.finest("Start discovering devices");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
try {
synchronized(lock) {
lock.wait();
}
if (searchForServices.size() > 0) {
waitForDevices = new CountDownLatch(searchForServices.size());
waitForDevices.await();
}
}
catch (InterruptedException e) {
LOG.log(Level.WARNING, "Error waiting to terminate discovery", e);
}
LOG.finest(servicesDiscovered.size() + " services discovered");
LOG.finest("Device discovery completed");
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Error initializing Bluetooth", e);
}
}
private class GDiscoveryListener implements DiscoveryListener {
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
try {
String name = rd.getFriendlyName(false);
boolean isMine = NAME.equals(name);
LOG.info("Discovered: " + name + "(" + rd.getBluetoothAddress() + ")"
+ (isMine ? "" : " - ignoring"));
if (!isMine)
return;
if (!rd.isAuthenticated()) {
LOG.finest("Try to pair with " + name
+ " PIN: " + PIN);
boolean paired = RemoteDeviceHelper.authenticate(rd, PIN);
LOG.info("Pair with " + name + (paired ? " succesfull" : " failed"));
}
int transID = discoveryAgent.searchServices(null, UUIDS, rd, discoveryListener);
searchForServices.put(transID, rd);
LOG.finest("Searching for services for " + name + " with transaction " + transID);
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), e);
} catch (IOException e) {
LOG.log(Level.WARNING, "Error connecting ", e);
} catch (Throwable t) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), t);
}
}
public void inquiryCompleted(int respCode) {
synchronized(lock) {
lock.notify();
}
switch (respCode) {
case DiscoveryListener.INQUIRY_COMPLETED :
LOG.fine("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
LOG.fine("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
LOG.fine("INQUIRY_ERROR");
break;
default :
LOG.fine("Unknown Response Code - " + respCode);
break;
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String rd = searchForServices.get(transID).getBluetoothAddress();
//searchForServices.remove(transID);
switch (respCode) {
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
LOG.fine(rd + ": The service search completed normally");
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
LOG.fine(rd + ": The service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch(int)");
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
LOG.warning(rd + ": An error occurred while processing the request");
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
LOG.info(rd + ": No records were found during the service search");
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
LOG.warning(rd + ": The device specified in the search request could not be reached or the local device could not establish a connection to the remote device");
break;
default:
LOG.warning(rd + ": Unknown Response Code - " + respCode);
break;
}
if (waitForDevices != null)
waitForDevices.countDown();
}
public void servicesDiscovered(int transID, ServiceRecord[] srs) {
LOG.info("Services discovered in transaction " + transID + " : " + srs.length);
for (ServiceRecord sr : srs) {
LOG.info(sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
servicesDiscovered.add(sr);
}
}
}
public static void main(String[] args) {
new Test().connect();
}
}
I had the same problem while connecting to a Bluetooth earpiece. Like you I was also searching for more than one service at a time and It always returned SERVICE_SEARCH_DEVICE_NOT_REACHABLE. So, I tried searching for only one service and it worked. So, try modifying your code as:
...
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003)}

Categories

Resources