I exported a java api abc.war file deployed into the "server", which returns the null([]) values, when I am calling get method from the Postman. This is working fine in local system but not in server.
Connection con= getConnection();
List<QuestionsModel> lstQuestions=new ArrayList<QuestionsModel>();
try
{
if(con!=null)
{
CallableStatement cstmt = null;
ResultSet rs = null;
cstmt = con.prepareCall("{call GetQuestions()}");
cstmt.execute();
rs = cstmt.getResultSet();
while (rs.next()) {
QuestionsModel questionsModel=new QuestionsModel();
questionsModel.setQuestionID(rs.getInt("QuestionID"));
questionsModel.setQuestion(rs.getString("Question"));
lstQuestions.add(questionsModel);
}
con.close();
System.out.println("Hello from GetQuestions Repository");
return lstQuestions;
}
}
catch (SQLException e) {
e.printStackTrace();
}
return lstQuestions;
Expected : Return list of objects(QuestionData)
Errors: No errors.
Related
I using Npgsql 3.2.2
I connect to database of Web server:
<add key="CONNECTION_STRING_WEBSERVER" value="Server=abctest.com;Port=5432;UserId=postgres;Password=postgres;Database=testdatabase;CommandTimeout=300;" />
My query to get data:
Dim sql="Select * from table1;"
my function:
private DataTable getData(string tableName)
{
DataSet ds = null;
DataTable tbl = null;
try
{
if (m_ConnectionExecute == null)
{
m_ConnectionExecute = new NpgsqlConnection(m_connString_web);
}
if (m_ConnectionExecute.State != ConnectionState.Open)
{
m_ConnectionExecute.Open();
}
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlCommand command = null;
try
{
command = CreateCommand(m_Parameters);
command.CommandText = m_commText;
command.Connection = m_ConnectionExecute;
adapter.SelectCommand = command;
ds = new DataSet();
adapter.Fill(ds, "Table1");
tbl = ds.Tables[0];
tbl.TableName = tableName;
ds.Tables.Clear();
}
catch (SqlException ex)
{
ds = null;
}
finally
{
if ( m_ConnectionExecute != null && m_ConnectionExecute.State != ConnectionState.Closed)
{
m_ConnectionExecute.Close();
}
}
}
catch (Exception e)
{
ds = null;
tbl = null;
}
return tbl;
}
I using Timer : 5s will call function getData.
But sometimes, function getData not respond and my program can't continue next process.
The problem only occur when Timer run some days and database put on a web server.
Notes: I have 5 Timer run auto access database.
what is the cause? or limit of postgresql?
Why Npgsql sometimes not responding?
I'm playing with Sonarqube plugin for Jenkins. How can I effectively solve this trivial violation he is complaining about without changing the logic?
Note: I need to validate the connections separetely ( ConnectionManager, statistics, keepAlive, .. ).
`
public void executeProcedure( final RequestProcessor consumer ) throws SQLException {
final String procedure = consumer.getProcedure();
final String idUrl = consumer.getIdUrl();
final PreparedStatementRegisterer stmRegisterer = consumer.getRegisterer();
// Autoclosable removed to allow ad hoc connection validation
Connection conn = null;
boolean execSuccess = false;
try{
conn = newConnection();
conn = checkOrChangeConnection(conn, false);
boolean hasResultSet = false;
try( CallableStatement statement = (OracleCallableStatement)conn.prepareCall(procedure) ){
...
stmRegisterer.prepareStatement(statement, idUrl);
statement.setQueryTimeout(QUERY_TIMEOUT);
hasResultSet = statement.execute();
execSuccess = true;
if(hasResultSet){
...
try ( ResultSet rs = statement.getResultSet() ) {
while ( rs.next() ) {
consumer.handleRow( rs );
}
}
}else{
...
consumer.getFieldsFromResult( statement );
}
}
}catch(Exception ex){
LOGGER.log( LogEntries.StorProcErr, ex.getMessage() );
throw new Exception( (!execSuccess ? "Error preparing and executing statement.":"Error during results reading.")+" Cause: "+ex) );
}finally{
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("\n Error closing connection on executeStoredProc. Cause: "+e+" \n"); // log
}
}
}
My idea is to add some more logging and re-throw the same exception after the log "StorProcErr". Is there a better approach?
Thanks
I want to execute a method periodically, this method get informations from database it show it into a label, I tried the following code :
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//update information
miseAjour();
}
}, 0, 2000);
when i run the main program, the background service run also normaly but when the informations changes on db i get this exception:
Exception in thread "Timer-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = Timer-0
And this is the code of method miseAjour :
public void miseAjour(){
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
int nbrAderent = rs.getInt("nbrAderent");
rs.close();
stmt.close();
connect.commit();
connect.close();
main_nbrAdrTot.setText(nbrAderent + "");
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can Timer for this, but I would recommend to use the JavaFX provided API called as ScheduledService.
ScheduledService is made to execute the same Task at regular intervals and since it creates a Task internally, there are API which help you to bind the value to the UI controls.
ScheduledService<Object> service = new ScheduledService<Object>() {
protected Task<Object> createTask() {
return new Task<Object>() {
protected Object call() {
// Call the method and update the message
updateMessage(miseAjour());
return object; // Useful in case you want to return data, else null
}
};
}
};
service.setPeriod(Duration.seconds(10)); //Runs every 10 seconds
//bind the service message properties to your Label
label.textProperty().bind(service.messageProperty()); // or use your label -> main_nbrAdrTot
Inside the dbcall method miseAjour, return the value that you have fetched and you want to update the label with :
public String miseAjour(){
String nbrAderent = null;
try {
dbConnection db = new dbConnection();
Connection connect = db.connectiondb();
connect.setAutoCommit(false);
Statement stmt= connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
return nbrAderent;
}
Finnaly i resolved the problem ,here is the code :
public class TimerServiceApp {
public void start() throws Exception {
TimerService service = new TimerService();
service.setPeriod(Duration.seconds(10));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
main_nbrAdrTot.setText(t.getSource().getMessage());
}
});
service.start();
}
private class TimerService extends ScheduledService<Integer> {
private final StringProperty nbrTotAderent = new SimpleStringProperty();
public final void setTotalAderentNumber(String value ) {
nbrTotAderent.set(value);
}
public String getTotalAderentNumber() throws SQLException {
String nbrAderent = null;
ResultSet rs=null;
Statement stmt=null;
Connection connect=null;
try {
dbConnection db = new dbConnection();
connect = db.connectiondb();
connect.setAutoCommit(false);
stmt= connect.createStatement();
rs = stmt.executeQuery("SELECT count(*) as nbrAderent FROM gss_aderent ");
nbrAderent = String.valueOf(rs.getInt("nbrAderent"));
connect.commit();
} catch (SQLException ex) {
Logger.getLogger(SimpleController.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
rs.close();
stmt.close();
connect.close();
}
System.out.println(" Total aderent number updated to :" + nbrAderent + " Aderents ");
return nbrAderent;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() throws SQLException {
nbrTotAderent.setValue(getTotalAderentNumber());
updateMessage(getTotalAderentNumber());
return Integer.parseInt(getTotalAderentNumber());
}
};
}
}
} `
and i called this service by :
TimerServiceApp s = new TimerServiceApp();
s.start();
i dont know if the solution is optimised but it work :) thank you #ItachiUchiha i took the solution from yout answer in the following link
I have searched for the solution but couldn't make it work. Here is the summary. I am trying to implement a webservice which runs on Glassfish 2.1 that implements a synchronous JMS Request-Response using Temporary queue. It sends a message to another Glassfish application running on remote server. I am able to send the message and process it but when the final message is sent back to temporary queue, the webservice gets the response as null. Here is the code:
private Message requestReply(String msg, Queue jmsRequestResponse, ConnectionFactory jmsRequestRespConnFactory) {
javax.jms.Connection conn = null;
javax.jms.MessageConsumer consumer = null;
javax.jms.Message replyMsg = null;
javax.jms.Session sess = null;
try {
logger.debug("[requestreply input message[" + msg);
conn = jmsRequestRespConnFactory.createConnection();
conn.start();
sess = conn.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
javax.jms.Message reqMessage = sess.createTextMessage(msg);
javax.jms.Destination replyDestination = (jmsRequestResponse instanceof javax.jms.Queue) ? sess.createTemporaryQueue() : sess.createTemporaryTopic();
reqMessage.setJMSReplyTo(replyDestination);
sess.createProducer(jmsRequestResponse).send(reqMessage);
replyMsg = consumer.receive(60000);
consumer.close();
sess.close();
conn.close();
} catch (JMSException ex) {
logger.debug("exception in requestreply");
} finally {
if (consumer != null) {
try {
consumer.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return replyMsg;
}
what am I missing here?? When I print the replyMsg, it is always null.
I have the following methods that are encountering some sort of failure with my database. No error is being written to my console, so I'm confused. I'm using JDBC and Google AppEngine. Can anyone help me, please? Thanks.
public List<Bulletin> getApprovedBulletins() {
List<Bulletin> bulletins = new ArrayList<Bulletin>();
try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
statement.executeQuery("select * from bulletins where approved = true");
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
Bulletin bulletin = new Bulletin();
bulletin.setId(resultSet.getInt("id"));
bulletin.setDate(resultSet.getDate("bulletin_date"));
bulletin.setName(resultSet.getString("name"));
bulletin.setSubject(resultSet.getString("subject"));
bulletin.setNote(resultSet.getString("bulletin"));
bulletins.add(bulletin);
}
resultSet.close();
connection.close();
return bulletins;
}
catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
private Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/cpc";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
return null;
}
return conn;
}
If you're using eclipse check the markers tab for errors. Note that the driver must be in the application server folder as well in order to work. Not sure why you don't get any errors in the console though...
Problem solved. I found a place to print out a message to my console, and it turns out I needed to add the following to appengine-web.xml, which I have done.
<sessions-enabled>true</sessions-enabled>