Results 1 to 5 of 5
  1. #1
    caho is offline Member
    Join Date
    Nov 2009
    Posts
    4
    Rep Power
    0

    Default seeking help for HttpServlet implements CometProcessor

    Hi yesterday I spend the whole day trying to get Comet working with an httpServlet. I tried simply copy pasting this tutorial:
    ibm.com/developerworks/web/library/wa-cometjava/index.html
    (This is my first post, i cant post links)

    But it is just not working !

    I modified server.xml like this (commented out my default port, and added the NIOprotocol to port 8180):
    Java Code:
     <!--Connector port="8180" protocol="HTTP/1.1" 
                   connectionTimeout="20000" 
                   redirectPort="8443" /-->
    <Connector connectionTimeout="20000" port="8180" protocol="org.apache.
    coyote.http11.Http11NioProtocol" redirectPort="8443"/>
    And in the JSP page i edited the URL to:
    Java Code:
    var url = "ht tp:// localhost:8180/WebApplication1/TomcatWeatherServlet "
    That is localhost / name of application / name of httpServlet
    (spelling error is because I cant post links)

    I also had to implement an empty stop(); method in the messagesender class. Otherwise no error after adding JDOM


    My problem: The application show up in my browser, but nothing happens when I click the button.

    Would anyone be so kind and test if they can make the tutorial code work.
    Thanks
    Caho

    System:
    Windows 7 x64 RC
    Firefox 3.5 default browser
    Netbeans 6.7

    TomcatWeatherServlet
    Java Code:
    import com.sun.syndication.feed.synd.SyndEntry;
    import com.sun.syndication.feed.synd.SyndFeed;
    import com.sun.syndication.io.SyndFeedInput;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.catalina.CometEvent;
    import org.apache.catalina.CometProcessor;
    
    public class TomcatWeatherServlet extends HttpServlet implements CometProcessor {
    
        private MessageSender messageSender = null;
        private static final Integer TIMEOUT = 60 * 1000;
    
        @Override
        public void destroy() {
            messageSender.stop();
            messageSender = null;
    
        }
    
        @Override
        public void init() throws ServletException {
            messageSender = new MessageSender();
            Thread messageSenderThread =
                    new Thread(messageSender, "MessageSender[" + getServletContext()
    .getContextPath() + "]");
            messageSenderThread.setDaemon(true);
            messageSenderThread.start();
    
        }
    
        public void event(final CometEvent event) throws IOException, ServletException {
            HttpServletRequest request = event.getHttpServletRequest();
            HttpServletResponse response = event.getHttpServletResponse();
            if (event.getEventType() == CometEvent.EventType.BEGIN) {
                request.setAttribute("org.apache.tomcat.comet.timeout", TIMEOUT);
                log("Begin for session: " + request.getSession(true).getId());
                messageSender.setConnection(response);
                Weatherman weatherman = new Weatherman(95118, 32408);
                new Thread(weatherman).start();
            } else if (event.getEventType() == CometEvent.EventType.ERROR) {
                log("Error for session: " + request.getSession(true).getId());
                event.close();
            } else if (event.getEventType() == CometEvent.EventType.END) {
                log("End for session: " + request.getSession(true).getId());
                event.close();
            } else if (event.getEventType() == CometEvent.EventType.READ) {
                throw new UnsupportedOperationException("This servlet does not accept data");
            }
    
        }
    
        private class MessageSender implements Runnable {
    
        protected boolean running = true;
        protected final ArrayList<String> messages = new ArrayList<String>();
        private ServletResponse connection;
        private synchronized void setConnection(ServletResponse connection){
            this.connection = connection;
            notify();
        }
        public void send(String message) {
            synchronized (messages) {
                messages.add(message);
                log("Message added #messages=" + messages.size());
                messages.notify();
            }
        }
        public void run() {
            while (running) {
                if (messages.size() == 0) {
                    try {
                        synchronized (messages) {
                            messages.wait();
                        }
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                }
                String[] pendingMessages = null;
                synchronized (messages) {
                    pendingMessages = messages.toArray(new String[0]);
                    messages.clear();
                }
                try {
                    if (connection == null){
                        try{
                            synchronized(this){
                                wait();
                            }
                        } catch (InterruptedException e){
                            // Ignore
                        }
                    }
                    PrintWriter writer = connection.getWriter();
                    for (int j = 0; j < pendingMessages.length; j++) {
                        final String forecast = pendingMessages[j] + "<br>";
                        writer.println(forecast);
                        log("Writing:" + forecast);
                    }
                    writer.flush();
                    writer.close();
                    connection = null;
                    log("Closing connection");
                } catch (IOException e) {
                    log("IOExeption sending message", e);
                }
            }
        }
    
            private void stop() {
                throw new UnsupportedOperationException("Not yet implemented");
            }
        }
    
        private class Weatherman implements Runnable{
    
        private final List<URL> zipCodes;
        private final String YAHOO_WEATHER = "ht tp ://weather.yahooapis.com/forecastrss?p=";
    
        public Weatherman(Integer... zips) {
            zipCodes = new ArrayList<URL>(zips.length);
            for (Integer zip : zips) {
                try {
                    zipCodes.add(new URL(YAHOO_WEATHER + zip));
                } catch (Exception e) {
                    // dont add it if it sucks
                }
            }
        }
    
       public void run() {
           int i = 0;
           while (i >= 0) {
               int j = i % zipCodes.size();
               SyndFeedInput input = new SyndFeedInput();
               try {
                   SyndFeed feed = input.build(new InputStreamReader(zipCodes.get(j).openStream()));
                   SyndEntry entry = (SyndEntry) feed.getEntries().get(0);
                   messageSender.send(entryToHtml(entry));
                   Thread.sleep(30000L);
               } catch (Exception e) {
                   // just eat it, eat it
               }
               i++;
           }
       }
    
        private String entryToHtml(SyndEntry entry){
            StringBuilder html = new StringBuilder("<h2>");
            html.append(entry.getTitle());
            html.append("</h2>");
            html.append(entry.getDescription().getValue());
            return html.toString();
        }
    }
    
    }
    index.jsp
    Java Code:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "ht tp :// ww w.w3.org/TR/html4/loose.dtd">
    
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Comet Weather</title>
            <SCRIPT TYPE="text/javascript">
                function go(){
                    var url = "ht tp ://localhost:8180/WebApplication1/TomcatWeatherServlet"
                    var request =  new XMLHttpRequest();
                    request.open("GET", url, true);
                    request.setRequestHeader("Content-Type","application/x-javascript;");
                    request.onreadystatechange = function() {
                        if (request.readyState == 4) {
                            if (request.status == 200){
                                if (request.responseText) {
                                    document.getElementById("forecasts").innerHTML =
    request.responseText;
                                }
                            }
                            go();
                        }
                    };
                    request.send(null);
                }
            </SCRIPT>
        </head>
        <body>
            <h1>Rapid Fire Weather</h1>
            <input type="button" onclick="go()" value="Go!"></input>
            <div id="forecasts"></div>
        </body>
    </html>
    server.xml
    Java Code:
    <?xml version='1.0' encoding='utf-8'?>
    
    
    <Server port="8105" shutdown="SHUTDOWN">
    
      <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
      <Listener className="org.apache.catalina.core.JasperListener" />
      <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
    
      <GlobalNamingResources>
    
        <Resource name="UserDatabase" auth="Container"
                  type="org.apache.catalina.UserDatabase"
                  description="User database that can be updated and saved"
                  factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
                  pathname="conf/tomcat-users.xml" />
      </GlobalNamingResources>
    
      
      <Service name="Catalina">
      
        
    	<Connector connectionTimeout="20000" port="8180" protocol="org.apache.coyote.http11.Http11NioProtocol" redirectPort="8443"/>
    
        <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    
    
        <Engine name="Catalina" defaultHost="localhost">
    
    
          <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                 resourceName="UserDatabase"/>
    
    
          <Host name="localhost"  appBase="webapps"
                unpackWARs="true" autoDeploy="true"
                xmlValidation="false" xmlNamespaceAware="false">
    
          </Host>
        </Engine>
      </Service>
    </Server>
    Last edited by caho; 11-04-2009 at 10:19 AM.

  2. #2
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    843
    Rep Power
    6

    Default

    Hi,
    No one will have time to execute.Have u tried to unzip and put "WeatherServer.zip"? under webapp folder of Tomcat?
    Ramya:cool:

  3. #3
    caho is offline Member
    Join Date
    Nov 2009
    Posts
    4
    Rep Power
    0

    Default

    Quote Originally Posted by RamyaSivakanth View Post
    Hi,No one will have time to execute.
    Hope is green ... or pink! :D

    Quote Originally Posted by RamyaSivakanth View Post
    Have u tried to unzip and put "WeatherServer.zip"? under webapp folder of Tomcat?
    I hadnŽt, but I have now, and it gave me the same result unfortunately.

    Can you perhaps direct me to a more stripped down CometProceesor "Hello world"?

    IŽll look around myself now.

    Any other suggestions?

    Thanks again

  4. #4
    caho is offline Member
    Join Date
    Nov 2009
    Posts
    4
    Rep Power
    0

    Default

    OK. I got something simple working from this tutorial:
    ht tp ://ww w.ajaxprojects.com/ajax/tutorialdetails.php?itemid=438#start

    It uses httpServlet and jQuery, and not CometProcessor. But as I understand it, I will need CometProcessor, to keep pushing data, right?

    I think maybe my problems are related to web.xml, which for the project I initially described (not the link in this post, sorry, they are both called Weather), looks like this:
    Java Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="ht tp://java.sun.com/xml/ns/javaee" xmlns:xsi="ht tp ://ww w.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ht tp://java.sun.com/xml/ns/javaee ht tp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
        </web-app>
    Which seems wrong to me, because it does not describe the servlet or the mapping, as does the jQuery tutorial:
    Java Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="ht tp://java.sun.com/xml/ns/javaee" xmlns:xsi="ht tp://ww w.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ht tp://java.sun.com/xml/ns/javaee ht tp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <servlet>
            <description>Weather Data provider</description>
            <display-name>Weather Data provider</display-name>
            <servlet-name>WeatherServlet</servlet-name>
            <servlet-class>ajaxify.WeatherServlet</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>WeatherServlet</servlet-name>
            <url-pattern>/WeatherServlet</url-pattern>
        </servlet-mapping>
    
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
        </web-app>

  5. #5
    caho is offline Member
    Join Date
    Nov 2009
    Posts
    4
    Rep Power
    0

    Default

    OK, Solved.
    I imported the whole project into Netbeans and deleted WeatherServlet and JettyWeatherServlet. I then had a look at the web.xml, which looked like this:
    Java Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" xmlns="ht tp://java.sun.com/xml/ns/javaee" xmlns:xsi="ht tp://ww w.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ht tp://java.sun.com/xml/ns/javaee ht tp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <servlet>
            <servlet-name>WeatherServlet</servlet-name>
            <servlet-class>org.developerworks.comet.TomcatWeatherServlet</servlet-class> 
    		<!-- Change the above to use the other servlets -->
        </servlet>
        <servlet-mapping>
            <servlet-name>WeatherServlet</servlet-name>
            <url-pattern>/Weather</url-pattern>
        </servlet-mapping>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
            </welcome-file-list>
        </web-app>
    The thing was that when recreating the application I had not been aware of the web.xml, therefore the URL pattern had not been set. I tried linking directly to the class. That was wrong.
    Now it is working.

Similar Threads

  1. HTTPServlet library
    By Robert_85 in forum Advanced Java
    Replies: 1
    Last Post: 04-10-2009, 09:28 PM
  2. Request Scope in HttpServlet
    By rkpasunoori in forum Java Servlet
    Replies: 1
    Last Post: 11-13-2008, 06:43 AM
  3. Help with dice game...student seeking advice
    By waparson in forum New To Java
    Replies: 3
    Last Post: 07-21-2008, 04:31 PM
  4. HttpServlet
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-17-2007, 08:46 PM
  5. How to implements cryptation in a java
    By paul in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 06:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •