Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. package pl.cornersoft.test;
  2.  
  3. import java.sql.*;
  4.  
  5. public class NotificationTest {
  6.  
  7. public static void main(String args[]) throws Exception {
  8. Class.forName("org.postgresql.Driver");
  9. String url = "jdbc:postgresql://192.168.23.159:5432/michal";
  10.  
  11. Connection lConn = DriverManager.getConnection(url,"michal","123");
  12.  
  13. Listener listener = new Listener(lConn);
  14.  
  15. listener.start();
  16.  
  17. }
  18.  
  19. }
  20.  
  21. class Listener extends Thread {
  22.  
  23. private Connection conn;
  24. private org.postgresql.PGConnection pgconn;
  25.  
  26. Listener(Connection conn) throws SQLException {
  27. this.conn = conn;
  28. this.pgconn = (org.postgresql.PGConnection)conn;
  29. Statement stmt = conn.createStatement();
  30. stmt.execute("LISTEN virt");
  31. stmt.close();
  32. }
  33.  
  34. public void run() {
  35. while (true) {
  36. try {
  37. Thread.currentThread().sleep(1000);
  38. Statement stmt = conn.createStatement();
  39. ResultSet rs = stmt.executeQuery("SELECT 1");
  40. rs.close();
  41. stmt.close();
  42.  
  43. org.postgresql.PGNotification notifications[] = pgconn.getNotifications();
  44. if (notifications != null) {
  45. for (int i=0; i<notifications.length; i++) {
  46. System.out.println("Got notification: " + notifications[i].getName());
  47. System.out.println("Got notification: " + notifications[i].getParameter());
  48. System.out.println("Got notification: " + notifications[i].getPID());
  49. System.out.println("Got notification: " + notifications[i].getClass().getName());
  50.  
  51. }
  52. }
  53.  
  54. // wait a while before checking again for new
  55. // notifications
  56. Thread.sleep(500);
  57. } catch (SQLException sqle) {
  58. sqle.printStackTrace();
  59. } catch (InterruptedException ie) {
  60. ie.printStackTrace();
  61. }
  62. }
  63. }
  64.  
  65. }
  66. /*
  67. class Notifier extends Thread {
  68.  
  69. private Connection conn;
  70.  
  71. public Notifier(Connection conn) {
  72. this.conn = conn;
  73. }
  74.  
  75. public void run() {
  76. while (true) {
  77. try {
  78. Statement stmt = conn.createStatement();
  79. stmt.execute("NOTIFY mymessage");
  80. stmt.close();
  81. Thread.sleep(2000);
  82. } catch (SQLException sqle) {
  83. sqle.printStackTrace();
  84. } catch (InterruptedException ie) {
  85. ie.printStackTrace();
  86. }
  87. }
  88. }
  89.  
  90. }*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement