⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httppushhandler.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    */   public void push(PushDataItem item) throws ServletException, IOException   {      if (closed()) return;      synchronized(pushQueue) {         pushQueue.addElement( item );         pushToBrowser();      }   }   /**    * Pushing messages in the queue to the browser    */   private void pushToBrowser() throws ServletException, IOException   {      if (log.isLoggable(Level.FINER)) log.finer("Entering pushToBrowser() ...");      synchronized(pushQueue) {         if(pushQueue.size() == 0)            return;         if(!isBrowserReady() ) {            log.info("Waiting until browser is ready to send " + pushQueue.size() + " messages");            return;         }         //setting Http push connection to false.         if (handlesMultipart) {            if (log.isLoggable(Level.FINE)) log.fine("Pushing multipart, pushQueue.size=" + pushQueue.size());            /* Every line which is sent to the browser overwrites the former one               Problems: (Linux/netscape)               1. The watch-wait cursor is displayed, until the doGet() leaves.               2. Resizing the browser window doesn't resize the content.               We help us by displaying a specialized little 'Connection-Window'               which holds the connection, the other application windows are               running fine then.            */            synchronized(outMulti) {               outMulti.println("Content-Type: text/html");               outMulti.println();               StringBuffer buf = new StringBuffer(head);               boolean isMessage = false;               // Collect all messages, pings etc from the queue ...               for( int i = 0; i < pushQueue.size(); i++ ) {                  PushDataItem item = (PushDataItem)pushQueue.elementAt(i);                  buf.append(item.data);                  if (item.type == PushDataItem.MESSAGE) isMessage = true;               }               if (isMessage)                  setBrowserIsReady(false); // Force browser to tell us when it is ready               buf.append(tail);               if (log.isLoggable(Level.FINEST)) log.finest("Sending to callbackFrame:\n" + buf.toString());               outMulti.println(buf.toString());               outMulti.println();               outMulti.println("--End");               outMulti.flush();               log.fine("Push content queue successfully sent as multipart.");               pushQueue.clear();            }         }         else {            log.fine("Pushing plain, pushQueue.size=" + pushQueue.size());            /*               Problems: (Linux/netscape)               1. The watch-wait cursor is displayed, until the doGet() leaves.               2. Resizing the browser window doesn't resize the content.               3. Browser only refreshes after one line is full                  (depending on current width every 3 messages)                  So the message should contain some <p> to force a refresh               4. Every line which is sent again to the browser is written after                  the previous one resulting in a list of ten rows.            */            synchronized(outPlain) {               StringBuffer buf = new StringBuffer();               if (firstPush) {                  buf.append(head);               }               else                  buf.append("<script language='JavaScript' type='text/javascript'>\n");               boolean isMessage = false;               // Collect all messages, pings etc from the queue ...               for( int i = 0; i < pushQueue.size(); i++ ) {                  PushDataItem item = (PushDataItem)pushQueue.elementAt(i);                  buf.append(item.data);                  if (item.type == PushDataItem.MESSAGE) isMessage = true;               }               if (isMessage)                  setBrowserIsReady(false); // Force browser to tell us when it is ready               // bug, thanks to Just: buf.append(tail);               if (log.isLoggable(Level.FINEST)) log.finest("Sending plain to callbackFrame:\n" + buf.toString());               outPlain.println(buf.toString());               outPlain.println("</script><p />\n");               outPlain.flush();               log.fine("Push content queue successfully sent.");               pushQueue.clear();            }         }      }      firstPush = false;   }   /**    * Pushes received message back to browser or applet.     * <p>    * Browser: Calls the update method in the parentframe of the callback frame    * The data must be Javascript code    * </p>    * <p>    * Applet: The callbacks are java-serialized Map for key/qos etc.    * </p>    */   public String update(String sessionId, UpdateKey updateKey, byte[] content, UpdateQos updateQos) {      try {         if (log.isLoggable(Level.FINE)) log.fine("update '" + updateKey.getOid() + "'");         if(callbackInterceptor != null) {            callbackInterceptor.update(sessionId, updateKey, content, updateQos);         }         String pushStr="";         String codedKey     = Global.encode(updateKey.toXml().trim(), BlasterHttpProxyServlet.ENCODING );         String codedContent = Global.encode(new String(content), BlasterHttpProxyServlet.ENCODING );         String codedQos     = Global.encode(updateQos.toXml().trim(), BlasterHttpProxyServlet.ENCODING );         pushStr = "if (parent.update != null) parent.update('"+codedKey+"','"+codedContent+"','"+codedQos+"');\n";         push(new PushDataItem(PushDataItem.MESSAGE, pushStr));      }      catch(Exception e) {         e.printStackTrace();         log.severe(e.toString());      }      return "<qos/>"; // TODO: Async wait on return value from browser/applet   }   /**    * Display a popup alert message containing the error text.    * <p />    * This method wraps your text into javascript/alert code    * and escapes "\n" and "'" characters    *    * @param text The error text    */   static public final String alert(String text)   {      StringBuffer retStr = new StringBuffer();      retStr.append("<html><body>\n");      retStr.append("<script language='JavaScript' type='text/javascript'>\n");      String tmp = ReplaceVariable.replaceAll(text, "'", "\\'");      retStr.append("alert(\'" + ReplaceVariable.replaceAll(tmp, "\n", "\\n'+\n'") + "');\n");      retStr.append("</script>\n");      retStr.append("</body></html>\n");      log.warning("Sending alert to browser: " + text);      return retStr.toString();   }   /**    * Calls the message method in the parentframe of the callback frame.    * <p />    * See callback.js message() method.    * Can be used by applications to send a message to the browser.    * @param text This must be Javascript code (usually a message string)    */   public void message( String text )   {      try {         String codedText = Global.encode(text, BlasterHttpProxyServlet.ENCODING);         push(new PushDataItem(PushDataItem.LOGGING, "if (parent.message != null) parent.message('"+codedText+"');\n"));      }      catch(Exception e) {         log.severe(e.toString());      }   }   /**    * Calls the error method in the parentframe of the callback frame.    * <p />    * See callback.js error() method, which shows an alert window.    * @param text This must be Javascript code (usually an error string)    */    /*   public void error(String text)   {      try {         String codedText = Global.encode(text, BlasterHttpProxyServlet.ENCODING);         push(new PushDataItem(PushDataItem.LOGGING, "if (parent.error != null) parent.error('"+codedText+"');\n"));      }      catch(Exception e) {         log.error(ME,e.toString());      }   }    */   /**    * calls the ping method in the parentframe of the callback frame    * The data must be Javascript code    * @param state The string "refresh"<br />    *              When login is done successfully, state="loginSucceeded" is sent    *              one time    */   public void ping(String state) throws ServletException, IOException   {      if (!isBrowserReady()) {         log.warning("Browser seems not to be ready, forcing a push nevertheless (checking browser with ping)");         setBrowserIsReady(true);      }      push(new PushDataItem(PushDataItem.PING, "if (parent.ping != null) parent.ping('" + state + "');\n"));   }   /**    * This is the browser response for our previous ping.    */   public void pong()   {      if (closed()) return;      if (pingThread != null) pingThread.pong();   }   /**    * Ping the browser, to avoid that the web server or the browser    * closes the http connection after a vendor specific timeout.    * <p />    * Note that the ping sends some bytes as well, the netscape browser    * for example closes the http connection if the amount of bytes per second    * falls below a certain level.    * <p />    * The browser responses with 'pong' which allows us to check if the browser    * is still here.    */   private class HttpPingThread extends Thread   {      private HttpPushHandler pushHandler;      private final long PING_INTERVAL;      private boolean pingRunning = true;      /** We wait for a browser response (pong) after out ping */      private int waitForPong = 0;      private long counter = 0L;      /**       * Response from the browser on our ping.       * <p />       * Sometimes the browser is fine but suddenly a pong is missing,       * for example ... "refresh-2084", "refresh-2086", ...<br />       * Number 2085 was just missing in the logs.<br />       * So we reset the waitForPong counter, and accept a sometimes missing pong.       */      public void pong()      {         if (log.isLoggable(Level.FINE)) log.fine("Received pong, current waitForPong=" + waitForPong + ", counter=" + counter);         waitForPong = 0; // not waitForPong--; if (waitForPong<0) waitForPong=0; since we don't care about delay, we are happy if the browser does respond somehow      }      public void stopThread()      {         pingRunning = false;      }      /**       * @param pingInterval How many milli seconds sleeping between the pings       * @param loginName For debugging only       */      HttpPingThread(HttpPushHandler pushHandler, long pingInterval, String loginName) {         this.pushHandler = pushHandler;         this.PING_INTERVAL = pingInterval;         if (log.isLoggable(Level.FINER)) log.finer("Entering constructor HTTP ping interval=" + pingInterval + " millis");      }      public void run() {         if (log.isLoggable(Level.FINER)) log.finer("Pinging browser ...");         while (pingRunning) {            try {               Thread.sleep(PING_INTERVAL);               if (pingRunning == false)                  break;               counter++;            }            catch (InterruptedException i) { }            try {               //if (false) {  //// Switched off !!!!!               if (waitForPong > 2) {  // Allow three pongs delay over slow connections               // This ping doesn't work over the internet??????                  log.warning("Browser seems to have disappeared, no response for my ping=" + counter + ", missing " + waitForPong + " responses. Closing connection.");                  pushHandler.cleanup();                  stopThread();               }               else {                  String text = "refresh-" + counter;                  if (log.isLoggable(Level.FINE)) log.fine("Sending ping '" + text + "'  to browser ...");                  pushHandler.ping(text);                  waitForPong++;               }            } catch(Exception e) {               //error handling: browser closed connection.               log.warning("You tried to ping=" + counter + " a browser who is not interested. Close HttpPushHandler.");               pushHandler.cleanup();               stopThread();            }         }         if (log.isLoggable(Level.FINE)) log.fine("Ping thread dies ...");      }   } // class PingThread}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -