Android remote JDBC connection - android

I'm trying to query a Pervasive database on my file server which is on a network with several other computers. On the router, I've set the appropriate ports to forward to the file server which is running the PSQL engine.
by visitng ip4.me, I got the ip address of the router.
here's the code:
class Task implements Runnable {
public void run() {
String routerIP ="*.*.*.*"; //blanked it out for privacy reasons
//String url = "jdbc:pervasive://192.168.1.139:1583/DB"; // THIS WORKS LOCALLY
String url = "jdbc:pervasive://" + routerIP + ":1583/DB"; //this throws exception
String query = "select NAME from CUSTOMER";
Statement stmt;
try {
Class.forName("com.pervasive.jdbc.v2.Driver");
} catch (Exception e) {
Log.d("ClassNotFoundException:", e.toString());
toast1.show();
}
try {
Connection conn = DriverManager.getConnection(url, "username", "password");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int i = 1;
while (rs.next()) {
for (i = 1; i <= numberOfColumns; i++) {
Log.d("Data", rs.getString(i));
myStringArray1.add(rs.getString(i));
}
}
stmt.close();
conn.close();
} catch (SQLException ex) {
Log.d("Error", ex.toString());
toast2.show();
}
}
}
A couple of different things are happening. When I try the connection on the local wifi (same network as the file server), I get java.sql.SQLException: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
Attempting to use a 4G connection (what I intend to use), I get
java.net.ConnectException: failed to connect to /*.*.*.* (port 1583): connect failed: ETIMEDOUT (Connection timed out)
(again, I blanked out the ip for privacy reasons)

Related

Bluetooth connection problems

I have a client on a PC and a server on a tablet. I know the MAC addresses for both which means I do not do discoveries.
1. On the client if I use
connectString = "btspp://" + MACaddress + ":4;authenticate=false;encrypt=false;master=false";
It connects fine.
If I change the CN number (4) to anything else, it does not work. How is this number determined?
2. Everything works fine if the tablet is a Samsung with Android 5.0.2 When I use a Qunyico tablet with Android 10, it does not work. I get an error: Failed to connect; [10051] A socket operation was attempted to an unreachable network. What is the problem?
Client on PC – code taken from “Bluetooth-java-client-master”
public class IrcBluetoothClient {
private static void openConnection(String MACaddress) throws IOException {
// Tries to open the connection.
String connectString = "btspp://" + MACaddress + ":4;authenticate=false;encrypt=false;master=false";
StreamConnection connection = (StreamConnection) Connector.open(connectString);
if (connection == null) {
System.err.println("Could not open connection to address: " + MACaddress);
System.exit(1);
}
// Initializes the streams.
OutputStream output = connection.openOutputStream();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
// Starts the listening service for incoming messages.
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(new IncomingMessagesLoggingRunnable(connection));
// Main loop of the program which is not complete yet
LocalDevice localDevice = LocalDevice.getLocalDevice();
while (true) {
String toSend = reader.readLine();
byte[] toSendBytes = toSend.getBytes(StandardCharsets.US_ASCII);
output.write(toSendBytes);
System.out.println("[" + localDevice.getFriendlyName() + " - " +
localDevice.getBluetoothAddress() + "]: " + toSend);
System.exit(1);
}
Server on tablet – code taken from https://developer.android.com/guide/topics/connectivity/bluetooth
private static final UUID A_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public BTacceptConnections( BluetoothAdapter mBluetoothAdapter) {
// Use a temporary object that is later assigned to mmServerSocket
// because mmServerSocket is final.
BluetoothServerSocket tmp = null;
try {
// A_UUID is the app's UUID string, also used by the client code.
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, A_UUID);
} catch (IOException e) {
Log.e(TAG, "Socket's listen() method failed", e);
}
mmServerSocket = tmp;
// Closes the connect socket and causes the thread to finish.
public void cancel(){
try {
mmServerSocket.close();
}catch (IOException e){
}
runFlag = 1;
}
//***********************************************************************************************
//
// This thread runs all the time listening for incoming connections.
//
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned.
while (runFlag == 0) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket's accept() method failed", e);
break;
}
if (socket != null) { // If a connection was accepted
// A connection was accepted. Perform work associated with
// the connection in a separate thread.
// manageMyConnectedSocket(socket);
}else{
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
I know the MAC addresses for both which means I do not do discoveries.
Official Linux Bluetooth protocol stack BlueZ uses D-BUS API to establish bluetooth communication. If you check adapter-api, scanning will create device objects that you need to establish a communication which means discovering is not only done to retrieve MAC addresses only.
Your case might be the same, I would suggest doing discovery first.

Connecting to Local SQL Server 2008 from my Application

I am working on an Android App for my friend database class and I am a bit in a bind. I am having troubles establishing my connection. Can someone assist me with this? I have a local database, I don't know much about MS SQL server. Here is the information:
ip = "Ip address"; // i am inserting IPV4 IP of computer in this
db = "testing";
un = "xee";
pass = "1995";
port = "1433";
#SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String ConnectionURL = null;
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
ConnectionURL = "jdbc:jtds:sqlserver://" + ip +":"+port+";"+ "databaseName=" + db + ";user=" + un + ";password="+ password + ";";
}
catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return connection;
}
}
I am getting an error when trying to connect
E/error here 1 :: Network error IOException: failed to connect to /***.***.*.*** (port 1433) from /:: (port 35033): connect failed: ECONNREFUSED (Connection refused)
Is the user name / password definitely correct?
Is your SQL Server configured to 'mixed' authentication mode? https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/change-server-authentication-mode?view=sql-server-2017
Does the user account have sufficient permissions to access the database? Try setting the login account to be 'sysadmin', which will give it maximum privileges.
Check the Firewall (not if it's a local DB)

MongoDB on Android - socket timeout

I want to connect my Android app to remote MongoDB database:
try {
String str = "";
MongoClientURI uri = new MongoClientURI("mongodb://byulent:mypass#ds231549.mlab.com:31549/mydb");
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase db = mongoClient.getDatabase(uri.getDatabase());
MongoCollection<Document> photos = db.getCollection("photos");
FindIterable<Document> cursor = photos.find();
Iterator i = cursor.iterator();
while (i.hasNext()){
Log.d("obj", i.next().toString());
}
//Toast.makeText(context, "Succesfully connected to MongoDB", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("mongodb", e.getMessage());
}
But when I try to get data from DB, I see this error:
E/mongodb: Timed out after 30000 ms while waiting to connect. Client view of cluster state
is {type=UNKNOWN, servers=[{address=ds231549.mlab.com:31549, type=UNKNOWN, state=CONNECTING,
exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by
{java.net.SocketTimeoutException: failed to connect to ds231549.mlab.com/34.245.70.193
(port 31549) after 20000ms}}]
Why this error occurs and how to fix it?

WiFi P2P Connection user interaction bypass?

I am working on an Android application using WiFi Direct. The application is supposed to create a group in each device or search for peers and transfer a string to each peer, depending if the device has Internet connection or not. Also I'm able to discover the MACs of all nearby peers in case the device has Internet.
This is my code for getting the nearby devices, where groupCreated is a variable that states if this device has created a group via createGroup() or is indeed looking for peers:
private WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if (!groupCreated) {
Collection<WifiP2pDevice> refreshedPeers = peerList.getDeviceList();
String peerInfo = "Available peers: \n";
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
for (WifiP2pDevice peer : peers) {
peerInfo += "\nMAC: " + peer.deviceAddress + " - Name: " + peer.deviceName;
}
TextView peerDisplay = (TextView) findViewById(R.id.peerListText);
peerDisplay.setText(peerInfo);
connectPeers();
}
if (peers.size() == 0) {
Toast.makeText(ProviderActivity.this, "No peers found!",
Toast.LENGTH_SHORT).show();
}
}
}
};
This is the code for actually connecting to the peers:
public void connectPeers(){
for (WifiP2pDevice peer : peers) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = peer.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
String host = "192.168.69.1";
int port = 8888;
int len;
Socket socket = new Socket();
String sent = "Hi!";
byte buf[] = new byte[1024];
try {
/**
* Create a client socket with the host,
* port, and timeout information.
*/
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), 1000);
/**
* Create a byte stream from a JPEG file and pipe it to the output stream
* of the socket. This data will be retrieved by the server device.
*/
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = new ByteArrayInputStream(sent.getBytes(Charset.forName("UTF-8")));
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
System.out.println(e.toString());
}
/**
* Clean up any open sockets when done
* transferring or if an exception occurred.
*/ finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
Toast.makeText(ProviderActivity.this, "Failed to close the connection!",
Toast.LENGTH_SHORT).show();
}
}
}
}
}
#Override
public void onFailure(int reason) {
Toast.makeText(ProviderActivity.this, "Failed to connect to peer!",
Toast.LENGTH_SHORT).show();
}
});
}
}
This is the client side, the server side is an async task, taken from https://developer.android.com/guide/topics/connectivity/wifip2p.html#setup in the "Transferring Data" section. Since I always connect to group owners I hardcoded the IP address Android attributes to a GO in WiFi Direct (192.168.69.1).
With this code I'm able to create the group and connect to the peers, but when I try to create a socket and transfer data, in the peers a prompt appears for the user to accept or decline the connection. In the API guide there was no user interaction involved. What am I doing wrong?
Thanks for the attention.
Similar question here.
You can track the numerous requests for this feature here.
And finally, one work around for this that i found in one of the comments in the second link i shared. Read the comments in the given code carefully.

Why is my file descriptor to a bluetooth socket null?

Can someone please help me figure out why I can only get a null file descriptor to a Bluetooth socket opened via BluetoothServerSocket.accept()?
My goal is streaming video between two devices over bluetooth, by writing video to a file descriptor on one side and reading it from a file descriptor on the other side. My Bluetooth connection is good, I can send raw data back and forth, but I can only get a file descriptor on the client side. On the server side, using the same code, I can only get a null file descriptor. In the debugger I can see a file descriptor on the server side at mySocket.mSocketIS.this$0.fd, but I can't figure out how to get access to it. Can anyone help? This is Android 4.4.2, here's my code:
First the broken code (Server side):
// Listen for an incoming Bluetooth connection
class AcceptThread extends Thread
{
// Thread that accepts incoming bluetooth connections
public AcceptThread()
{
try
{
// Open a listening server socket. This is non-blocking
btServerSocket = BA.listenUsingRfcommWithServiceRecord("ServerApp", videoUUID);
} catch(IOException e){ btServerSocket = null; }
} // AcceptThread()
public void run()
{
BluetoothSocket btSocket = null;
// Listen until exception or we have a socket
while(true)
{
try
{
// Blocking call to accept an incoming connection. To get out of this, call cancel() which closes the socket, causing .accept() to throw an exception
btSocket = btServerSocket.accept();
// If we get here, we're connected!
Field pfdField = btSocket.getClass().getDeclaredField("mPfd");
pfdField.setAccessible(true);
ParcelFileDescriptor pfd = (ParcelFileDescriptor) pfdField.get(btSocket);
// >>> ERROR - pfd is null <<<< I can see a fd at mySocket.mSocketIS.this$0.fd;, but how do I access it?
FileDescriptor myFd = pfd.getFileDescriptor();
// ... blah blah...
Now the working code (Client side):
// Connect to a remote device as the client (we are the client)
class ConnectThread extends Thread
{
// ctor
// remoteUUID - The UUID of the remote device that we want to connect to
public ConnectThread(BluetoothDevice btDevice, UUID remoteUUID)
{
// Get a BT socket to connect with the given BluetoothDevice
try
{
// MY_UUID is the app's UUID string, also used by the server code
btClientSocket = btDevice.createRfcommSocketToServiceRecord(remoteUUID);
}catch(Exception e){ postUIMessage("ConnectThread exception: " + e.toString()); }
} // ConnectThread ctor
public void run()
{
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
try
{
// Connect the device through the socket. This will block until it succeeds or throws an exception. To get out, call cancel() below, which will cause .connect() to throw an exception.
btClientSocket.connect();
Field pfdField = btClientSocket.getClass().getDeclaredField("mPfd");
pfdField.setAccessible(true);
ParcelFileDescriptor pfd = (ParcelFileDescriptor) pfdField.get(btClientSocket);
FileDescriptor myFd = pfd.getFileDescriptor(); // Pass this to Recorder.setOutputFile();
// Yay myFd is good!
I found a fix on my side regarding this issue, we are using bluetooth as a server too. I found the file descriptor from the LocalSocket field in BluetoothSocket. My goal was to get teh file and close it.
int mfd = 0;
Field socketField = null;
LocalSocket mSocket = null;
try
{
socketField = btSocket.getClass().getDeclaredField("mSocket");
socketField.setAccessible(true);
mSocket = (LocalSocket)socketField.get(btSocket);
}
catch(Exception e)
{
Log ( "Exception getting mSocket in cleanCloseFix(): " + e.toString());
}
if(mSocket != null)
{
FileDescriptor fileDescriptor =
mSocket.getFileDescriptor();
String in = fileDescriptor.toString();
//regular expression to get filedescriptor index id
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);
while(m.find()) {
Log ( "File Descriptor " + m.group(1));
mfd = Integer.parseInt(m.group(1));
break;
}
//Shutdown the socket properly
mSocket.shutdownInput();
mSocket.shutdownOutput();
mSocket.close();
mSocket = null;
try { socketField.set(btSocket, mSocket); }
catch(Exception e)
{
Log ("Exception setting mSocket = null in cleanCloseFix(): " + e.toString());
}
//Close the file descriptor when we have it from the Local Socket
try {
ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.adoptFd(mfd);
if (parcelFileDescriptor != null) {
parcelFileDescriptor.close();
Log ( "File descriptor close succeed : FD = " + mfd);
}
} catch (Exception ex) {
Log ( "File descriptor close exception " + ex.getMessage());
}
}

Categories

Resources