Connecting GWT and PostgreSQL - google-app-engine

I've been working with GWT and appengine. Now I want to change my database to a relational one. I prefer PostgreSQL over MySQL because of the schema architecture.
I already work in projects with JDBC, but I cannot make it work in my appengine project.
What am I doing wrong?

I think you are mistake. If you want your backend to connect to JDBC you have to disable appengine.
I recommend creating a new web project with the google eclipse plugin but without appengine. Then copy all the source files and start from there.
I let you my class to connect to PostgreSQL vua JDBC
public class ConexionBD
{
private Vector <Connection> connections = new Vector<Connection>();
protected int cantCon=3;
private static ConexionBD pool;
private ConexionBD(){
for (int i= 0; i< cantCon;i++)
connections.add(connect());
}
public static ConexionBD getPoolConnection(){
if (pool== null)
pool =new ConexionBD();
return pool;
}
private Connection connect()
{
try
{
//Setear driver
Class.forName ("org.postgresql.Driver").newInstance ();
Connection con = DriverManager.getConnection ("jdbc:postgresql://localhost:5432/llevomisnegocios","postgres","root");
return con;
}
catch (SQLException e){
System.out.println("Mensaje Error al Conectar: " + e.getMessage());
//System.out.println("Stack Trace: " + e.getStackTrace());
return null;
}catch (Exception ex){
System.out.println("Mensaje Error al Conectar: " + ex.getMessage());
//System.out.println("Stack Trace: " + ex.getStackTrace());
return null;
}
}
public void closeConnections(){
for (int i=0; i<connections.size();i++)
{
try
{
connections.elementAt(i).close();
}
catch(Exception e)
{
System.out.println("Mensaje Error: " + e.getMessage());
System.out.println("Stack Trace: " + e.getStackTrace());
}
}
}
public Connection getConnection(){
Connection c = null;
if (connections.size()>0)
c = connections.remove(0);
else{
c = connect();
System.out.println("PoolConnection: Conexion Exitosa con la BD");
}
return c;
}
public void realeaseConnection(Connection c){
connections.add(c);
}
}

Related

BaseX parrallel Client

I have client like this :
import org.basex.api.client.ClientSession;
#Slf4j
#Component(value = "baseXAircrewClient")
#DependsOn(value = "baseXAircrewServer")
public class BaseXAircrewClient {
#Value("${basex.server.host}")
private String basexServerHost;
#Value("${basex.server.port}")
private int basexServerPort;
#Value("${basex.admin.password}")
private String basexAdminPassword;
#Getter
private ClientSession session;
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
this.session = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
}
}
It is a singleton injected in a service which run mulitple queries like this :
Query query = client.getSession().query(finalQuery);
return query.execute();
All threads query and share the same session.
With a single thread all is fine but with multiple thread I get some random (and weird) error, like the result of a query to as a result of another.
I feel that I should put a synchronized(){} arround query.execute() or open and close session for each query, or create a pool of session.
But I don't find any documentation how the use the session in parrallel.
Is this implementation fine for multithreading (and my issue is comming from something else) or should I do it differently ?
I ended creating a simple pool by adding removing the client from a ArrayBlockingQueue and it is working nicely :
#PostConstruct
private void createClient() throws IOException {
log.info("##### Creating BaseX client session {}", basexServerPort);
final int poolSize = 5;
this.resources = new ArrayBlockingQueue < ClientSession > (poolSize) {
{
for (int i = 0; i < poolSize; i++) {
add(initClient());
}
}
};
}
private ClientSession initClient() throws IOException {
ClientSession clientSession = new ClientSession(basexServerHost, basexServerPort, UserText.ADMIN, basexAdminPassword);
return clientSession;
}
public Query query(String finalQuery) throws IOException {
ClientSession clientSession = null;
try {
clientSession = resources.take();
Query result = clientSession.query(finalQuery);
return result;
} catch (InterruptedException e) {
log.error("Error during query execution: " + e.getMessage(), e);
} finally {
if (clientSession != null) {
try {
resources.put(clientSession);
} catch (InterruptedException e) {
log.error("Error adding to pool : " + e.getMessage(), e);
}
}
}
return null;
}

Unable to Connect SQL Server when using MultiThreading

I am try to connect SQL Server using multi-threading the execute SQL query on tables.
When I try to connect SQL server it's working fine without any issue, but when try to connect using thread mechanism it displaying exception.
Here is my code can exception message please let me know how to resolve this issue.
using System;
using System.Data.SqlClient;
using NUnit.Framework;
using System.Threading;
namespace ThreadSQLConnect
{
[TestFixture]
public class SQLConnect
{
private static object threadLock = new object();
[Test]
public void temp()
{CreateThread(1); }
public static void CreateThread(int ThreadCount)
{
Thread[] workerThread = new Thread[ThreadCount];
for (int i = 0; i < ThreadCount; i++)
{
workerThread[i] = new Thread(new ThreadStart(ConnectDBAndExecuteQueryWithLock));
workerThread[i].Name = i.ToString();
workerThread[i].Start();
}
}
public static void ConnectDBAndExecuteQueryWithLock()
{
lock (threadLock)
{
try
{
string sqlQuery = "insert into tblMasterLookup Values (" + Thread.CurrentThread.Name + ",'Test','2.0','Myapplication',GetDate())";
string connectionString = string.Format("Server={0}; Database = {1}; User Id = {2}; Password = {3};",
"serverNname",
"Databasename",
"ReadOnlyUser",
"ReadOnly12");
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch(Exception e)
{ Console.WriteLine(e.StackTrace); }
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
command.CommandTimeout = 80;
command.ExecuteNonQuery();
Console.WriteLine("Executed Thread.. " + Thread.CurrentThread.Name);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
Here is exception message

Using H2 database server how to notify changes to clients (JMS messaging)

I am successfully using H2 database in AUTO_SERVER mode so that a database file is shared among a number of desktop clients on a network transparently.
This way a server is elected among the clients and all other clients read from the tcp server.
What I'm missing is how a client or the server can notify all other desktop clients something has been changed in the database.
Right now I'm using a JGroups channel to let all clients comunicate one with each other however this is another point of failure and another leader election algorithm which runs in parallel with H2.
Isn't there any other method?
I have read about the JMS (Java Message Service Java API) which is supported in some databases. Any hint for H2?
Thanks
EDIT:
The following code is an adaptation of the current answer, if I start the Sender first (set args as "sender") he connects as server to the H2 database, then I execute Receiver (set args as "receiver") in remote machines and they connect as clients.
Yet only the server receives notifications, clients don't receive anything.
This makes sense from what I currently know: a trigger is only called on the server, a user defined function called from a client or server is called on the client or server but not across all clients (and server) connected to the database.
So is there a way to adapt the below to notify all connected instances of a change in the database?
import java.io.File;
import java.sql.*;
import java.util.concurrent.atomic.AtomicLong;
import org.h2.tools.TriggerAdapter;
public class TestSimpleDB2
{
public static void main(String[] args) throws Exception
{
//final String url = "jdbc:h2:mem:test;multi_threaded=true";
final String url = "jdbc:h2:" + File.separator + "mnt/testdir/PlanIGS" + File.separator
+ "persondb;create=true;AUTO_SERVER=TRUE;multi_threaded=true";
Connection conn = DriverManager.getConnection(url);
Statement stat = conn.createStatement();
boolean isSender = false;
args = new String[]
{
"sender"
};
for (String arg : args)
{
if (arg.contains("receiver"))
{
System.out.println("receiver starting");
isSender = false;
}
else if (arg.contains("sender"))
{
System.out.println("sender starting");
isSender = true;
}
}
if (isSender)
{
stat.execute("create alias wait_for_change for \""
+ TestSimpleDB2.class.getName()
+ ".waitForChange\"");
stat.execute("create table test(id identity)");
stat.execute("create trigger notifier "
+ "before insert, update, delete, rollback "
+ "on test call \""
+ TestSimpleDB2.Notifier.class.getName() + "\"");
Thread.sleep(1000);
for (int i = 0; i < 10; i++)
{
System.out.println("Sender: I change something...");
stat.execute("insert into test values(null)");
Thread.sleep(2000);
}
}
else
{
new Thread()
{
public void run()
{
try
{
Connection conn = DriverManager.getConnection(url);
for (int i = 0; i < 10; i++)
{
conn.createStatement().execute(
"call wait_for_change(100000)");
System.out.println("Receiver: event received");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
conn.close();
}
static AtomicLong modCount = new AtomicLong();
public static void waitForChange(long maxWaitMillis)
{
synchronized (modCount)
{
try
{
modCount.wait(maxWaitMillis);
}
catch (InterruptedException e)
{
// ignore
}
}
}
public static class Notifier extends TriggerAdapter
{
public void fire(Connection conn, ResultSet oldRow, ResultSet newRow)
throws SQLException
{
modCount.incrementAndGet();
synchronized (modCount)
{
modCount.notifyAll();
}
}
}
}
H2 does not implement JMS (in fact I don't know of a database that does). However, you could build a simple notify mechanism within H2, using a trigger and a user defined function, as follows. Please note this would require the multi-threaded mode in H2, which is not fully tested yet. Because of that, it might make sense to use a separate database for messaging than the database you use for your data.
import java.sql.*;
import java.util.concurrent.atomic.AtomicLong;
import org.h2.tools.TriggerAdapter;
public class TestSimpleDb {
public static void main(String[] args) throws Exception {
final String url = "jdbc:h2:mem:test;multi_threaded=true";
Connection conn = DriverManager.getConnection(url);
Statement stat = conn.createStatement();
stat.execute("create alias wait_for_change for \"" +
TestSimpleDb.class.getName() +
".waitForChange\"");
stat.execute("create table test(id identity)");
stat.execute("create trigger notifier " +
"before insert, update, delete, rollback " +
"on test call \"" +
TestSimpleDb.Notifier.class.getName() + "\"");
new Thread() {
public void run() {
try {
Connection conn = DriverManager.getConnection(url);
for (int i = 0; i < 10; i++) {
conn.createStatement().execute(
"call wait_for_change(10000)");
System.out.println("Receiver: event received");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
Thread.sleep(500);
for (int i = 0; i < 10; i++) {
System.out.println("Sender: I change something...");
stat.execute("insert into test values(null)");
Thread.sleep(1000);
}
conn.close();
}
static AtomicLong modCount = new AtomicLong();
public static void waitForChange(long maxWaitMillis) {
synchronized (modCount) {
try {
modCount.wait(maxWaitMillis);
} catch (InterruptedException e) {
// ignore
}
}
}
public static class Notifier extends TriggerAdapter {
public void fire(Connection conn, ResultSet oldRow, ResultSet newRow)
throws SQLException {
modCount.incrementAndGet();
synchronized (modCount) {
modCount.notifyAll();
}
}
}
}

java.sql.SQLException: Problems with loading native library/missing methods: no ttJdbc1121 in java.library.path

I am getting this error while trying to connect to timesten DB configured in my system:
java.sql.SQLException: Problems with loading native library/missing methods: no ttJdbc1121 in java.library.path
Here is my code:
try {
Class.forName("com.timesten.jdbc.TimesTenDriver");
conn = DriverManager
.getConnection("jdbc:timesten:direct:dsn=TT_Alias");
System.out.println(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am using java 5 & attached ttjdbc5.jar in the build path.
can someone help please?
ttJdbcCS1122.dll is in bin folder of TimesTen home please copy that to lib folder, now start running you program it will work if rest of configuration is correct.
// /JDBC Driver
static final String JDBC_DRIVER = “com.timesten.jdbc.TimesTenDriver”;
static final String DB_URL = “jdbc:timesten:client:TTC_Server=serverIp;TTC_Server_DSN=DSN;TCP_PORT=PortNo”;
// DB Credential
static final String username = “***”;
static final String password = “****”;
System.out.println(“Registering database …”);
Class.forName(JDBC_DRIVER);
//Connecting to db
System.out.println(“Connecting to database …”);
conn = DriverManager.getConnection(DB_URL, username, password);

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

Resources