I am trying to connect my android program to Hana database using jdbc driver.
It was running well when try to connect to SQL database server. But I when try to connect to Hana database, it cannot be connected.
I have added jdbc in my library, and also added some permission in android. But it does not work. The database could be connected.
Here's java code the I used.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
private static String ip = "172.10.x.x";
private static String port = "xxxx";
private static String Classes = "com.sap.db.jdbc.Driver";
private static String db = "DBTEST";
private static String usr = "databaseuser";
private static String pass = "databasepassword";
private static String url = "jdbc:sap://"+ip+":"+port+"/?databaseName="+db+"&user="+usr+"&password="+pass+";";
private Connection connection = null;
public void connectButtonClick(View v){initializeMainComponents();}
public void initializeMainComponents()
{
try {
Class.forName(Classes);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(url, usr,pass);
Toast.makeText(getApplicationContext(), "Database connected", Toast.LENGTH_LONG).show();
}
catch(ClassNotFoundException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Database connection error", Toast.LENGTH_LONG).show();
}
catch(SQLException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Database connection failure", Toast.LENGTH_LONG).show();
}
}
Related
I have written code using JDBC to create registration page in Android Studio. I create database in SQL Server 2019. In addition I tried to connect from the code to MSSQL database and insert values, but while I run the app I'm getting the error:
login failed for user.
I have examined many options that can cause this error and I fixed them. For example: The server authentication is SQL Server authentication,the TCP option at the server is enabled, I have the relevant permissions of the user, also I check the if the firewall is the cause for this error. However, I continue to receive the error.
The connection class:
public class ConnectionClass {
public static String ip= "***.***.*.*:1433"; //
public static String user_name ="****";
public static String password = "****";
public static String database = "tests";
}
The Registeration class:
EditText email;
EditText password;
EditText confirmPassword;
Button sign_up;
EditText name;
Connection connection1;
Statement statement;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_parent);
email = (EditText) findViewById(R.id.editTextTextEmailAddress2);
password = (EditText) findViewById(R.id.editTextTextPassword);
confirmPassword = (EditText) findViewById(R.id.editTextTextPassword2);
sign_up = (Button) findViewById(R.id.button);
name = (EditText) findViewById(R.id.editTextTextPassword3);
status = (TextView) findViewById(R.id.status);
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ParentSignUp.registerUser().execute("");
}
});
}
public class registerUser extends AsyncTask<String, String, String>{
String z ="";
Boolean isSuccess = false;
public registerUser() {
super();
}
#Override
protected void onPreExecute() {
status.setText("Sending Data to Database");
}
#Override
protected void onPostExecute(String s) {
name.setText("");
email.setText("");
password.setText("");
confirmPassword.setText("");
}
#Override
protected String doInBackground(String... strings) {
try {
connection1 = connection_class(ConnectionClass.user_name.toString(), ConnectionClass.password.toString(),
ConnectionClass.database.toString(), ConnectionClass.ip.toString());
if (connection1 == null) {
z = "Check Internet Connection";
}
else {
String sql = "INSERT INTO test (name,password, email) VALUES ('example', 'example', 'example')";
statement = connection1.createStatement();
statement.executeUpdate(sql);
}
}
catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return null;
}
}
#SuppressLint("NewApi")
public Connection connection_class (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");
connectionUrl = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";"+"password=" + password + ";";
connection = DriverManager.getConnection(connectionUrl);
}catch (Exception e){
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}
I am just working on an android application written in native Java. I am using a server in this application so I am working with WebSockets.
I am getting this error
java.net.ProtocolException: Expected HTTP 101 response but was '200 OK'
while trying to connect to ws://echo.websocket.org and I don't know why. I am new to working with WebSockets so I am really lost on that one.
That's my activity where I try to establish the connection. The important part is in InitiateSocketConnection() function
package com.example.rockpaperscissors;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
public class Loby extends AppCompatActivity {
private String name;
private WebSocket webSocket;
private String Server_Path = "ws://echo.websocket.org";
private RecyclerView recyclerView;
private PlayersAdapter playersAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loby);
name = getIntent().getStringExtra("name");
InitiateSocketConnection();
}
private void InitiateSocketConnection() {
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(Server_Path).build();
webSocket = client.newWebSocket(request,new Socket_Listener());
client.dispatcher().executorService().shutdown();
}
private class Socket_Listener extends WebSocketListener
{
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
runOnUiThread(()->
{
Toast.makeText(Loby.this,"Socket connected successfully!",Toast.LENGTH_LONG).show();
initializeView();
});
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
}
#Override
public void onFailure(WebSocket webSocket, Throwable t, #Nullable Response response) {
super.onFailure(webSocket, t, response);
runOnUiThread(()->
{
Throwable err = t;
Toast.makeText(Loby.this, "Socket was not connected!", Toast.LENGTH_LONG).show();
});
}
}
private void initializeView() {
recyclerView = findViewById(R.id.name_list);
playersAdapter = new PlayersAdapter(getLayoutInflater());
recyclerView.setAdapter(playersAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name",name);
playersAdapter.addItem(jsonObject);
webSocket.send(jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I don't think that's the issue but I permitted internet in manifest and this is my relevant implantation on the build.Gradle:
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
Thanks!
I had the same issue when using ws://echo.websocket.org. Changing it to ws://websocket-echo.com solved my problem.
I am new to couchbase lite implementation, i am working on Android platform and i have created a database,saved a simple document in it. Now i want to extract the database and view the document saved in it. I placed a sample json in raw folder, read from raw and converted to hashmap.
Below are all the details
CODE
DatabaseManager class to create database
package com.example.couchbasesample;
import android.content.Context;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.DatabaseConfiguration;
import java.io.File;
public class DatabaseManager {
private final static String DATABASE_NAME = "couchbase_test";
public Database database;
private static DatabaseManager instance = null;
public DatabaseManager(Context context) {
// Set database configuration
try {
// Set Database configuration
DatabaseConfiguration config = new DatabaseConfiguration(context);
File dir = context.getDir("COUCH_ANDROID",Context.MODE_PRIVATE);
config.setDirectory(dir.toString());
// Create / Open a database with specified name and configuration
database = new Database(DATABASE_NAME, config);
}
catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
public static DatabaseManager getSharedInstance(Context context) {
if (instance == null) {
instance = new DatabaseManager(context);
}
return instance;
}
}
MainActivity
package com.example.couchbasesample;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.couchbase.lite.MutableDocument;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
private DatabaseManager dbMgr;
#BindView(R.id.btnSave)
Button btnSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// Initialize couchbase lite database manager
dbMgr = new DatabaseManager(this);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
JSONObject customerJSON = new JSONObject(getFileFromResources(MainActivity.this, "samplecustomer"));
/* HashMap<String, JSONObject> customerTest = new HashMap<>();
customerTest.put("1", customerJSON);*/
HashMap<String, Object> yourHashMap = new Gson().fromJson(customerJSON.toString(), HashMap.class);
MutableDocument doc = new MutableDocument(yourHashMap);
// 3. Save document to database.
dbMgr.database.save(doc);
Toast.makeText(MainActivity.this, "saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
public static String getFileFromResources(Context context, String fileName) {
String json = null;
try {
InputStream is = context.getResources().openRawResource(
context.getResources().getIdentifier(fileName,
"raw", context.getPackageName()));
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return json;
}
}
WHAT I TRIED
I extracted the database using "Device file explorer" from android studio, when i save the app_COUCH_ANDROID folder and open .sqlite file in DB Browser for SQLite couldn't view the saved document instead it just shows up with random data i am unable to understand.
*Other than this i researched and found the following viewer,but unable to use this as its for MAC OS.
https://github.com/couchbaselabs/CouchbaseLiteViewer*
How i can view the couchbase lite database. Can somebody please help me out with this? Any help will be appreciated.
If you need to lookup documents stored in the database, use the getDocument or any of the Query APIs from within your app.
If you want to query the database outside of the content of the app, then you can use the cblite tool. This is a command line tool that will allow you to open and introspect the cblite2 database.
Any reason why you are trying to look up documents outside the context of the app that is embedding the database? You cannot view the data with a standard sqlite browser because the data is binary encoded and stored in Fleece format.
I am trying to make sure that what i choose on ComboBox will be the hostname during the connection i am going to attempt to do
if I hardcode the String Host connection works perfectly fine but I would like to use droplist to determine the host which i want to connect to
here is the code i am having
import javax.swing.*;
import java.awt.event.*;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;
import java.util.EmptyStackException;
#SuppressWarnings("serial")
public class welcomewindow extends JFrame {
public static void main(String[] args) {
#SuppressWarnings("unused")
welcomewindow frameTabel = new welcomewindow();
}
String host;
JButton blogin = new JButton("Login");
JLabel UIusername = new JLabel("Username",SwingConstants.LEFT);
JLabel Jumpbox = new JLabel("Choose your Jumpbox",SwingConstants.LEFT);
JLabel UIpassword = new JLabel("Password",SwingConstants.LEFT);
JTextField txuser = new JTextField(15);
//JComboBox ComboBox = new JComboBox();
#SuppressWarnings({ })
String[] J1J2 = {"ServerA", "ServerB"};
#SuppressWarnings({ "unchecked", "rawtypes" })
JComboBox JumpList= new JComboBox(J1J2);
JPasswordField pass = new JPasswordField(15);
#SuppressWarnings({ "rawtypes", "unchecked" })
welcomewindow(){
super("Login Authorization to Tracer");
setSize(300,150);
setLocation(500,280);
//panel.setLayout (null);
String[] J1J2 = {"ServerA", "ServerB"};
JComboBox JumpList= new JComboBox(J1J2);
UIusername.setVerticalAlignment(SwingConstants.CENTER);
UIpassword.setVerticalAlignment(SwingConstants.CENTER);
Jumpbox.setVerticalAlignment(SwingConstants.CENTER);
JLabel UIusername = new JLabel("Username",SwingConstants.LEFT);
JLabel UIpassword = new JLabel("Password",SwingConstants.LEFT);
JLabel Jumpbox = new JLabel("Choose Your Jumpbox",SwingConstants.LEFT);
blogin.setVerticalAlignment(SwingConstants.CENTER);
JumpList.setSelectedIndex(0);
JPanel panel = new JPanel();
panel.add(Jumpbox);
panel.add(JumpList);
panel.add(UIusername);
panel.add(txuser);
panel.add(UIpassword);
panel.add(pass);
panel.add(blogin);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
panel.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),"EnterButton1");
panel.getRootPane().getActionMap().put("EnterButton1",new AbstractAction(){
public void actionPerformed(ActionEvent ae)
{
String puname = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd = pass.getText();
if(puname.isEmpty() || ppaswd.isEmpty()){
JOptionPane.showMessageDialog(null,"Username Or Password Field is empty");
}
else{
blogin.doClick();
}
}
});
actionlogin();
}
public void actionlogin(){
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String puname1 = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd1 = pass.getText();
String host = (String) JumpList.getSelectedItem();
if(puname1.isEmpty() || ppaswd1.isEmpty()){
JOptionPane.showMessageDialog(null,"Username Or Password Field is empty");
}
else{
String puname = txuser.getText();
#SuppressWarnings("deprecation")
String ppaswd = pass.getText();
String command1="pwd";
int port=22;
String remoteFile="/home/bsoghmonian/test.txt";
System.out.println(host);
boolean sshconnected = false;
try
{
System.out.println(host);
JSch jsch = new JSch();
Session session = jsch.getSession(puname, host, port);
session.setPassword(ppaswd);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Crating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sshconnected = true;
System.out.println("SFTP Channel created.");
if(sshconnected){
instancewindow instancewelcome =new instancewindow();
instancewelcome.setVisible(true);
dispose();
}else{
throw new EmptyStackException();
}
............. till the end of the Program
The Issue I have here is even if I choose Server B user attempts to connect to ServerA I would like if user chooses ServerB the application attempts to connect the user to ServerB and when ServerA chosen then connects to ServerA
You defined the same JComboBox two times - you operate (change values) on a local one within welcomewindow(), but then you take JumpList.getSelectedItem() from the untouched global one, hence it's always the first option ;)
I am getting an exception for the following code. I am not able to understand what is UUID. Can anyone help to resolve this error? I have posted the code as well as error I am getting.
package wiki.nokia.example;
import java.io.IOException;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.L2CAPConnection;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
public class BluetoothServer implements Runnable {
private boolean listening = true;
private LocalDevice local_device;
private BtoothChat midlet;
private String deviceName;
private L2CAPConnection con;
/** Creates a new instance of BluetoothServer */
public BluetoothServer(BtoothChat midlet) {
this.midlet = midlet;
Thread t = new Thread(this);
t.start();
}
public void run(){
System.out.println("Starting server - please wait...");
try {
local_device = LocalDevice.getLocalDevice();
DiscoveryAgent disc_agent = local_device.getDiscoveryAgent();
local_device.setDiscoverable(DiscoveryAgent.LIAC);
String service_UUID = "9";
deviceName = local_device.getFriendlyName();
String url = "btl2cap://localhost:" + service_UUID + ";name=" + deviceName;
L2CAPConnectionNotifier notifier = (L2CAPConnectionNotifier)Connector.open(url);
con = notifier.acceptAndOpen();
while (listening) {
if (con.ready()){
byte[] b = new byte[1000];
con.receive(b);
String s = new String(b, 0, b.length);
System.out.println("Recieved from client: " + s.trim());
midlet.setAlert(s.trim());
send("Hello client, my name is: " + getName());
listening=false;
}
}
} catch(BluetoothStateException e){System.out.println(e);} catch(IOException f){System.out.println(f);}
}
private void send(String s){
byte[] b = s.getBytes();
try {
con.send(b);
} catch(IOException e){
System.out.println(e);
}
}
private String getName(){
return deviceName;
}
}
ERROR IS:
Starting server - please wait...
Uncaught exception: java.lang.NumberFormatException
at java.lang.Long.parseLong(Long.java:401)
at javax.bluetooth.UUID.<init>(), bci=166
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.createServiceRecord(), bci=26
at com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl.<init>(), bci=122
at com.sun.jsr082.bluetooth.btl2cap.Protocol.serverConnection(), bci=16
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrimImpl(), bci=24
at com.sun.jsr082.bluetooth.BluetoothProtocol.openPrim(), bci=14
at com.sun.midp.io.j2me.btl2cap.Protocol.openPrim(), bci=7
at javax.microedition.io.Connector.openPrim(), bci=327
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=3
at javax.microedition.io.Connector.open(), bci=2
at wiki.nokia.example.BluetoothServer.run(BluetoothServer.java:48)
at java.lang.Thread.run(), bci=11
You can find a definition of an UUID here. The problem is that the UUID you are using isn't appropriate. A value of '9' won't do.