Can't connect to Derby in Eclipse - database

I am trying to develop a web app with eclipse that uses a derby database and runs on tomcat.
My problem is that I cannot start the derby server with eclipse (it works fine out of CMD) and I cannot get my servlet to establish a connection with the database, each time I try I get the error:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.Jieren.servlets.Authenticator.testCredentials(Authenticator.java:84)
at com.Jieren.servlets.Authenticator.doPost(Authenticator.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
I do not have any xml files that do anything with the connection (I have seen web.xml and such that manage connections) but from what I have seen a connection should be possible via straight java code (which seemed easier to learn with as I am fairly new).
The code that I use to connect with is as follows.
Connection conn = null;
PreparedStatement prestat = null;
ResultSet pw = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/apache-tomcat-7.0.19/Databases/Jieren;" +
"user=Access;" +
"password=Entry");
prestat = conn.prepareStatement("SELECT password FROM logs WHERE username = ?");
prestat.setString(1, username);
pw = prestat.executeQuery();
if (password.equals(pw.toString())) answer = 1;
pw.close();
pw = null;
prestat.close();
prestat = null;
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
finally{
if (pw != null){
try { pw.close();} catch (SQLException e){;}
pw = null;
}
if (prestat != null){
try { prestat.close();} catch (SQLException e){;}
prestat = null;
}
if (conn != null){
try {conn.close();} catch(SQLException e) {;}
conn = null;
}
}
From what I have figured out from looking around, the code should work if everything else is configured correctly. connecting to the database via ij outside eclipse works, so I have a feeling that there is a setting or something that I need to write in eclipse to connect this.

The exception is telling you that your network server is not running. When your connection URL starts jdbc:derby://hostname, then you are telling Derby you wish to run in client-server mode, meaning that your client application will establish a TCP/IP connection to the Network Server. See this doc for how to setup and operate the Network Server: http://db.apache.org/derby/docs/10.8/adminguide/

Related

Codename one application is not able to connect with server using https request

We have created codename one application which using https request.
I have not made any changes in code.
Earlier the request could be sent using https but now their is a problem and i am unable to connect to the server using https request but i am able to connect same https url using postman.
The connection code snippet is following please refer it
new APIHandler().PropertiesLoad();
ConnectionRequest req = new ConnectionRequest() {
protected void handleErrorResponseCode(int code, String message) {
if (code != 200) {
// do something
}
}
};
req.setUrl(properties.getProperty("https_url"));
req.setPost(true);
req.setTimeout(Constant.TIMEOUT);
req.addArgument("FirstName", fName;
req.addArgument("SecondName", sName);
req.addArgument("BirthDate", bDate);
req.addArgument("Password", pWord);
NetworkManager.getInstance().addErrorListener((e) -> e.consume());
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
if (data == null) {
}
result = new String(data);
} catch (Exception e) {
//get nullpointer exception because result get null
result = "";
}
return result;

Apache Storm - Accessing database from SPOUT - connection pooling

Having a spout which on each tick goes to Postgre database and reads an additional row. The spout code looks as follows:
class RawDataLevelSpout extends BaseRichSpout implements Serializable {
private int counter;
SpoutOutputCollector collector;
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("col1", "col2"));
}
#Override
public void open(Map map, TopologyContext context, SpoutOutputCollector spoutOutputCollector) {
collector = spoutOutputCollector;
}
private Connection initializeDatabaseConnection() {
try {
Class.forName("org.postgresql.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
DATABASE_URI,"root", "root");
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
#Override
public void close() {
}
#Override
public void nextTuple() {
List<String> values = new ArrayList<>();
PreparedStatement statement = null;
try {
Connection connection = initializeDatabaseConnection();
statement = connection.prepareStatement("SELECT * FROM table1 ORDER BY col1 LIMIT 1 OFFSET ?");
statement.setInt(1, counter++);
ResultSet resultSet = statement.executeQuery();
resultSet.next();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int totalColumns = resultSetMetaData.getColumnCount();
for (int i = 1; i <= totalColumns; i++) {
String value = resultSet.getString(i);
values.add(value);
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
collector.emit(new Values(values.stream().toArray(String[]::new)));
}
}
What is the standard way how to approach connection pooling in Spouts in apache storm? Furthermore, is it possible to somehow synchronize the coutner variable accross multiple running instances within the cluster topology?
Regarding connection pooling, you could pool connections via static variable if you wanted, but since you aren't guaranteed to have all spout instances running in the same JVM, I don't think there's any point.
No, there is no way to synchronize the counter. The spout instances may be running on different JVMs, and you don't want them all blocking while the spouts agree what the counter value is. I don't think your spout implementation makes sense though. If you wanted to just read one row at a time, why would you not just run a single spout instance instead of trying to synchronize multiple spouts?
You seem to be trying to use your relational database as a queue system, which is probably a bad fit. Consider e.g. Kafka instead. I think you should be able to use either one of https://www.confluent.io/product/connectors/ or http://debezium.io/ to stream data from your Postgres to Kafka.

How to make a connection localhost and my database

I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful
Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

How to access sqlite database from webserver and insert record using web services in codenameone

I am developing one application in CN1 that has to do with database, I want the user to enter a pin generated for them. once the user entered the valid pin, the apps will be activated for usage. The problem am having now is how to access the database using webservices. I have followed the webservices wizard tutorial, but all my effort was futile.
This is my snippet code.
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
Please help me out. I dont know what to do next. Thanks
This is because you aren't accessing a webservice. You are trying to open a database with an http URL:
SQLException: path to 'C:\Users\EMMY_OLUWASEGUN.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db'
Triggered by:
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
The Database API is local to the device and not remote a webservice is something completely different.
Thanks for your response, Author of CN1. This is the full code below. I am using tomcat server on the local machine to test on the simulator. I am very sure if it works for me on the local machine's server, it will definitely work on the web server
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
Cursor c = myDataBase.executeQuery("select pin from PIN_TABLE where id = 1" );
if (c.next()) {
Row r = c.getRow();
String pin = r.getString(0);
Dialog.show("valid pin", pin, "Ok", "Ok");
} else if (!c.next()) {
Dialog.show("Invalid pin", "keep off", "ok", "ok");
}
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
This is the error code generated for me when I ran the code:
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://localhost:8085/CBT_PINS/folder/PINS.db to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
java.sql.SQLException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
[Network Thread] 0:0:0,0 - Codename One revisions: 375ed2c938445450f0983f0d18235f61e793a7ee2004
[Network Thread] 0:0:0,0 - Exception: java.io.IOException - path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
Rendering frame took too long 187 milliseconds
at org.sqlite.SQLiteConnection.open(SQLiteConnection.java:156)
at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:105)
at org.sqlite.JDBC.createConnection(JDBC.java:113)
at org.sqlite.JDBC.connect(JDBC.java:87)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7548)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7554)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Throw DirectoryServicesCOMException (0x80072020) when try to RefreshCache for DirectoryEntry

I write a very sample test program and run it as local system account in a domain machine. Here is the code look like:
static void Main(string[] args)
{
try
{
System.Console.Out.WriteLine("Test Start");
List<string> temp = new List<string>();
temp.Add(Environment.UserDomainName);
temp.Add("test");
temp.Add("test.com");
temp.Add("dc.test.com");
temp.Add("gc.test.com");
foreach (var i in temp)
{
using (HostingEnvironment.Impersonate())
{
System.Console.WriteLine("LDAP://{0}", i);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + i);
try
{
entry.RefreshCache();
string nativeGuid = entry.NativeGuid;
string path = entry.Path;
string server = entry.Options.GetCurrentServerName();
System.Console.WriteLine("{0} success!", i);
}
catch (Exception e)
{
System.Console.WriteLine("{0}\n {1}", i, e);
}
}
}
System.Console.Out.WriteLine("Test End");
}
catch (Exception e)
{
System.Console.Out.WriteLine("e:Main{0}", e.Message);
}
System.Console.In.ReadLine();
}
The NetBIOS name for the domain is "test", full domain name is "test.com". "dc.test.com" is the DC FQDN and "gc.test.com" is the GC FQDN.
It works fine for "test.com", "dc.test.com"" and "gc.test.com", but it throws DirectoryServicesCOMException (0x80072020) for "test" and "Environment.UserDomainName".
The detail running result is:
Test Start
LDAP://TEST
TEST
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test
test
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test.com
test.com success!
LDAP://dc.test.com
dc.test.com success!
LDAP://gc.test.com
gc.test.com success!
Test End
It works all fine if I run it as domian admin account. Any idea what cause this? Thanks a lots!
What are you actually trying to do? If you're on a machine joined to the domain, you should just do new DirectoryEntry().
As for your error, when you log on to Windows with a local account, the UserDomainName environment variable is set to the local computer name. If that machine's name is the same as the domain's NetBIOS name, then I wouldn't be surprised if Windows gets confused.

Resources