Servlet Output Streams and clearing

I am using servlets, and I want to be able to print something repeatedly. Well, that's not exactly true: I can print something repeatedly. Using a ServletOutputStream, it doesn't seem possible to clear what has already been written. Here's the code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class AlwaysTime extends HttpServlet {
     public void doPost(HttpServletRequest req, HttpServletResponse res)                throws ServletException, IOException {
          HttpServletResponse oldRes = res;
          Date now = new Date();
          res.setContentType("text/html");
          ServletOutputStream out = res.getOutputStream();
          out.println("<html>");
          out.println("<head>");
          out.println("<title>Clock</title>");
          out.println("</head>");
          out.println("<body>");
          out.println("<h1 align=\"Center\">");
          out.println(now.toString());
          out.println("</h1>");
          out.println("</body>");
          out.println("</html>");
          try {
             Thread.sleep(1000);
          } catch (InterruptedException ie) {}
          // Do nothing: wait for 1 second.
          doPost(req, oldRes);
     public void doGet(HttpServletRequest req, HttpServletResponse res)
          throws ServletException, IOException {
          doPost(req, res);
}This code prints the time every second, but I want to clear the previous output stream. I thought the code shown above would work, but of course, oldRes points to the same object as res. But I don't know how to clear an output stream, so that it is completely empty. Instead, each of the new lines are appended to the same output stream.
This doesn't only apply to servlet output streams: is there some way to clear the System output stream, for instance?
But mainly the servlet output stream ...

You would not want to use HTTP for this type of functionality. HTTP is known as a 'stateless' protocol that simply returns one exact response for each request. So, there is not way to 'clear' the stream (technically, you would not do so for 'normal' streams either, but when you add HTTP into the mix, the task is definitely not possible).
You could implement the above using a RSS feed, or by using HTTP meta-refresh tags on the page itself ot resubmit the requests every second (though this would be inefficient). An applet would also do the task.
- Saish

Similar Messages

  • Read Servlet output stream

    how can i read servlet output stream

    i m using SAX to create an XML.
    I set result to "Servlet Output Stream" as shown below :->
    SAXTransformerFactory saxTF = SAXTransformerFactory.newInstance();
    TransformerHandler th = saxTF.newTransformerHandler();
    Transformer t = th.getTransformer();
    StreamResult stRes = new StreamResult(res.getOutputStream());
    th.setResult(stRes);
    th.startDocument();
    what i want to wright the same xml result in file at the same time(parallel y).

  • REG:SERVLET OUTPUT STREAM

    I am trying to implement upload/view functionality..To view an uploaded txt file or html file,I am just flushing out the file contents into servlet's output stream..The content type has been set appropriately.
    The problem is for some html files ia m able to see the file contents in the browser,and for some html files,the browser displays a open/save dialog box..
    Can any1 explain me why this discrepency?Its the sam e code and same content type..why is it so?

    Thanks for ur reply...
    All i mentioned was in the same browser..PFB the code snippet
         ServletOutputStream pic = null;
         pic = response.getOutputStream();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte b[] = new byte[5*1024];
         while(true)
              int bytes = in.read(b);
              if(bytes == -1)
                   break;
              baos.write(b, 0, bytes);
         response.setContentLength(b.length);
         b = baos.toByteArray();
         pic.write(b, 0, b.length);
         pic.flush();
         pic.close()

  • Writing to servlet output stream

    Hi All,
    I am writing to a servlet(imageservlet) output stream in a jsp page two times as follows:
    <img src="\imageservlet?key=x1">
    <img src="\imageservlet?key=x2">
    It is causing memory errors. Do I have to take special precautions?
    Thanks inadvance.

    Hi,
    THis is my servlet code.
    import java.io.*;
    import java.io.StringWriter;
    import javax.servlet.http.*;
    import javax.servlet.*;
    import java.awt.Color;
    import com.trizetto.healthweb.service.GenerateImage;
    * Simple servlet to use with Image I/O generator
    public class GenerateImageServlet extends HttpServlet
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
         String className="PieChartGenerator";
         if(request.getParameter("keyName").equals("Pie"))
              className=PieChartGenerator";
         else if( request.getParameter("keyName").equals("Gantt") )
              className="GanttChartGenerator";
    try
    GenerateImage ge=
    (GenerateImage) Class.forName(className).newInstance();
    String type = ge.createImage(response.getOutputStream());
    response.setContentType(type);
    catch (Exception e)
    throw new ServletException(e);
    But this one does not generate image. The image is generated from the Graphics object of the Frame.
    Something like the following code:
    http://www.javaworld.com/javaworld/jw-05-2000/servlets/Servlets.zip
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p2.html
    http://www.javaworld.com/javaworld/jw-05-2000/jw-0505-servlets-p1.html
    I am using Java 1.1.
    I am running my app. in websphere. The error happens randomly while I am stopping the websphere application server.
    Thanks in advance.

  • Preventing servlet output stream to flush

    I increased the buffersize in the response object in order to make it possible for the entire jsp page to process before writing any output to the webclient.
    BUT since I use dynamic jsp-includes I fail to accomplish this, since according to the JSP1.3 specification the output stream is flushed before processing a dynamic include instruction.
    Is there a way I can make JSP to process the include and write output to buffer WITHOUT flushing it?
    Regards, Jon

    No I am using JSP 1.3. And I want to do the following:<%
    for (int i = 0; i < 5; i++) {
       // include("file_"+ i +".jsp");
    %>This to include file_0.jsp up to file_4.jsp.
    I assume the <jsp:include>tag is preprocessed hence only included once.

  • Having trouble Output streams and text formatting???

    Salutaions!
    I'm trying to write a peice of code that takes input from a file and outputs it in the following way: (1)Any string of two or more blank space is replaced by a single space. (2)All sentences start with an uppercase letter. Define a sentence as beginning after a ".", "?","!"
    This is what I got: Please help!
    import java.io.*;
    import java.util.*;
    public class Empty
    private static boolean cap;
    private static DataInputStream input;
    private static DataOutputStream output;
    private static String inputFile, outputFile;
    public static void main(String[] args) throws Exception
         input = new DataInputStream(new FileInputStream("a://in.txt"));
         output = new DataOutputStream(new FileOutputStream("a://out.txt"));
         char thisChar, lastChar = ' ';
         while(input.read() != -1)
         thisChar = ((char)input.read());
         if(lastChar != ' ' && thisChar != ' ')
              if(thisChar == '.' || thisChar == '?' || thisChar == '!')
              {    cap = true;
              output.writeChar(thisChar);
              lastChar = thisChar;
              else
              cap = false;
              output.writeChar(thisChar);
              lastChar = thisChar;
         output.close();
         input.close();

    one clear mistake i can see in this method is that you r calling input.read() twice every time. once in the if(input.read()..) statement and then in the statement
    thisChar = ((char)input.read());
    the byte read the first time is not captured anywhere.
    do you have some specific motive behind doing this?
    luck!
    y

  • Servlet output streaming problem

    Hi all !
              Given the following JSP/Servlet:
              <html>
              <body>
              Test
              <%
              out.println( "<h1>Countdown</h1>" );
              for ( int i = 10; i > 0; i-- ) {
              out.print( "<h1>" );
              out.print( i );
              out.println( "</h1>" );
              out.flush();
              try {
              // simulate access to an external system
              Thread.sleep( 1000 );
              catch ( InterruptedException e ) {}
              out.println( "<h1>Liftoff</h1>" );
              out.close();
              %>
              </body>
              </html>
              This prints out the numbers 10 to 0 with a seconds pause inbetween.
              This works on our development server. However, after uploading to the
              production server, the page is blank for ten seconds and then shows
              all the numbers in one chunk. The problem is that the out.flush()
              statement appearently is ignored by the weblogic server. No errors or
              exceptions in any logs.
              Is this a configuration issue ?
              Setup:
              * Weblogic 5.1
              * Linux Redhat 7.2
              Thanks.
              Pål O.
              

    Do you have a proxy in front of WL? Do you have a web proxy on the client
              side?
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com/coherence.jsp
              Tangosol Coherence: Clustered Replicated Cache for Weblogic
              "Pål O. Kristiansen" <[email protected]> wrote in message
              news:[email protected]...
              > Hi all !
              >
              > Given the following JSP/Servlet:
              >
              > <html>
              > <body>
              > Test
              > <%
              > out.println( "<h1>Countdown</h1>" );
              > for ( int i = 10; i > 0; i-- ) {
              > out.print( "<h1>" );
              > out.print( i );
              > out.println( "</h1>" );
              > out.flush();
              > try {
              > // simulate access to an external system
              > Thread.sleep( 1000 );
              > }
              > catch ( InterruptedException e ) {}
              > }
              > out.println( "<h1>Liftoff</h1>" );
              > out.close();
              > %>
              > </body>
              > </html>
              >
              > This prints out the numbers 10 to 0 with a seconds pause inbetween.
              > This works on our development server. However, after uploading to the
              > production server, the page is blank for ten seconds and then shows
              > all the numbers in one chunk. The problem is that the out.flush()
              > statement appearently is ignored by the weblogic server. No errors or
              > exceptions in any logs.
              >
              > Is this a configuration issue ?
              >
              > Setup:
              > * Weblogic 5.1
              > * Linux Redhat 7.2
              >
              > Thanks.
              >
              > Pål O.
              

  • How can I put an output stream (HTML) from a remote process on my JSF page

    Hello,
    I've a question if someone could help.
    I have a jsf application that need to execute some remote stuff on a different process (it is a SAS application). This remote process produces in output an html table that I want to display in my jsf page.
    So I use a socket SAS class for setting up a server socket in a separate thread. The primary use of this class is to setup a socket listener, submit a command to a remote process (such as SAS) to generate a data stream (such as HTML or graphics) back to the listening socket, and then write the contents of the stream back to the servlet stream.
    Now the problem is that I loose my jsf page at all. I need a suggestion if some one would help, to understand how can I use this html datastream without writing on my Servlet output stream.
    Thank you in advance
    A.
    Just if you want to look at the details .....
    // Create the remote model
    com.sas.sasserver.submit.SubmitInterface si =
    (com.sas.sasserver.submit.SubmitInterface)
    rocf.newInstance(com.sas.sasserver.submit.SubmitInterface.class, connection);
    // Create a work dataset
    String stmt = "data work.foo;input field1 $ field2 $;cards;\na b\nc d\n;run;";
    si.setProgramText(stmt);
    // Setup our socket listener and get the port that it is bound to
    com.sas.servlet.util.SocketListener socket =
    new com.sas.servlet.util.SocketListener();
    int port = socket.setup();
    socket.start();
    // Get the localhost name
    String localhost = (java.net.InetAddress.getLocalHost()).getHostAddress();
    stmt = "filename sock SOCKET '" + localhost + ":" + port + "';";
    si.setProgramText(stmt);
    // Setup the ods options
    stmt = "ods html body=sock style=brick;";
    si.setProgramText(stmt);
    // Print the dataset
    stmt = "proc print data=work.foo;run;";
    si.setProgramText(stmt);
    // Close
    stmt = "ods html close;run;";
    si.setProgramText(stmt);
    // get my output stream
    context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    ServletOutputStream out = response.getOutputStream();
    // Write the data from the socket to the response
    socket.write(out);
    // Close the socket listener
    socket.close();

    The system exec function is on the Communication palette. Its for executing system commands. On my Win2K system, the help for FTP is:
    "Ftp
    Transfers files to and from a computer running an FTP server service (sometimes called a daemon). Ftp can be used interactively. Click ftp commands in the Related Topics list for a description of available ftp subcommands. This command is available only if the TCP/IP protocol has been installed. Ftp is a service, that, once started, creates a sub-environment in which you can use ftp commands, and from which you can return to the Windows 2000 command prompt by typing the quit subcommand. When the ftp sub-environment is running, it is indicated by the ftp command prompt.
    ftp [-v] [-n] [-i] [-d] [-g]
    [-s:filename] [-a] [-w:windowsize] [computer]
    Parameters
    -v
    Suppresses display of remote server responses.
    -n
    Suppresses autologin upon initial connection.
    -i
    Turns off interactive prompting during multiple file transfers.
    -d
    Enables debugging, displaying all ftp commands passed between the client and server.
    -g
    Disables file name globbing, which permits the use of wildcard characters (* and ?) in local file and path names. (See the glob command in the online Command Reference.)
    -s:filename
    Specifies a text file containing ftp commands; the commands automatically run after ftp starts. No spaces are allowed in this parameter. Use this switch instead of redirection (>).
    -a
    Use any local interface when binding data connection.
    -w:windowsize
    Overrides the default transfer buffer size of 4096.
    computer
    Specifies the computer name or IP address of the remote computer to connect to. The computer, if specified, must be the last paramete
    r on the line."
    I use tftp all of the time to transfer files in a similar manner. Test the transfer from the Windows command line and copy it into a VI. Pass the command line to system exec and wait until it's done.

  • Servlet output not displayed properly in Internet Explorer

    Hi All,
    I'm developing a servlet which uploads a file. After the servlet parses the request body, it stores the file contents as a binary string in the database. While displaying the contents of the attached file, the IE(Internet Explorer) is ignoring all the newlines and spaces. IThe same uploaded file when viewed through Firefox browser is being displayed properly. I've added some debug statements to print the filecontent before sending it to servlet output stream. They look exactly as they were in the uploaded file. The MIME type is application/octet-stream.
    I've also made the response to accept "ISO-8859-1" and "UTF-8" charsets, yet the IE is not rendering the file contents properly. The code looks like this,
    response.setContentType("text/html; charset= ISO-8859-1, UTF-8");
    byte[] buff = attachment.getAttachObject();
    OutputStream out = response.getOutputStream();
    out.write(buff);
    out.close();
    I've tried using PrintWriter also. I've tried changing the content types, character encodings of request and response objects, still couldn't resolve the issue. What really baffles me is that when it's displaying properly in Firefox, why can't it render properly in IE? I'm using Win XP SP2, and IE version is 6.0.29. The content which is being sent to the output stream contains newline and space characters, but they are not displayed in the browser. Did any one face this sort of issue? Your help is highly appreciated.
    Thanks,
    Tarun.

    Hi,
    Thanks for looking into the issue. Let me tell you that I've tried keeping various content-types like text/plain, text/xml etc, but in none of those cases the IE rendered the output properly. But with the same content-type i.e text/html or text/plain, Firefox is able to render the file content properly. I've tried a brutal force approach like below,
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    String str = new String(attachment.getAttachObject());
    char[] buff = str.toCharArray();
    for(i=0;i< buff.length; i++)
    int n = (int)buff;
    if(n == 10)
    out.println();
    else
    out.print(buff[i]);
    out.close();
    I was trying to print a newline whenever I find a newline character in the file content. Even this didn't work. Please suggest me some way to get rid of this problem.

  • PDF Document as an Output Stream.

    Hi,
    I have created a PDFwriter class that easily creates and writes a PDF document stream to a fileout stream.I am using JSP to do the same.
    What i want to do now is directly send the stream to an output stream instead of a fileoutput stream. Question is which one??
    How do i pass it to response obj, (response.setOutputStream(System.out) does not work)
    I am Pasting some code so that you can understand what i mean( >> means next step)
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 30, 20); >>
    File file = new File("C:\\ePro\\PDFGenerator\\Report.pdf"); >> document.open();
    Table table = new Table(9); >> table.setPadding(0); >> table.setSpacing(1); >>
    table.addCell(new cell ("Any String",fontF); >> document.add(table); >> document.close(); >>
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    The above code creates a PDF file on my disk which i can then redirect. Eg
    response.setContentType("application/pdf");
    response.sendRedirect("Report.pdf");
    What i want now is to replace the constructor for PDFWriter with a different Output stream and directly write it to browser.
    Please help as i am stuck for quite some time now....

    byte[] pdfContent = PDFProcessor.getPDFStream(roleID,report,Integer.parseInt(languageID));
    response.setContentType("application/pdf");
    ServletOutputStream out = response.getOutputStream();
    System.out.println("Writing PDF");
    out.write(pdfContent);
    out.flush();

  • Servlet  output correct in ie and netscape, but not in portal

    I have a servlet that retrieves and xml document, applies a
    stylesheet, and uses PrintWriter to output the html.
    When I run the servlet, the output is correct in ie and netscape.
    So, I set the servlet up as a web portlet and have put it on a
    portal page.
    My problem: When I run the portal page, the mdashes and
    rsquotes, etc. show up in portal as question marks.
    I went into the provider.xml and added some information
    (contentType,charset), but that had no effect.
    Ideas appreciated.
    Thanks.

    I have been doing some research, and this appears to be some
    sort of character encoding/unicode problem.
    I have specified UTF-8 in my servlet. Does portal not work with
    UTF-8?
    Is there a setting somewhere that I can check in portal to
    verify what character encoding it is using? (ISO-8859-1, US-
    ASCII, etc?)
    This is a sample of my servlet code:
    public void DoGet(HttpServletRequest request, HttpServlet
    Response,response)
    throws ServletException, IOException
    DOMParser parser;
    XMLDocument xml,xsldoc;
    URL xslURL,xmlURL;
    String xmld = "";
    String xsld = "";
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try
    parser = new DOMParser();
    parser.setPreserveWhitespace(true);
    xslURL = createURL(xsld);
    parser.parse(xslURL);
    xsldoc = parser.getDocument();
    xmlURL = createURL(xmld);
    parser.parse(xmlURL);
    xml = parser.getDocument();
    XSLStylesheet xsl = new XSLStylesheet(xsldoc,xslURL);
    XSLProcessor processor = new XSLProcessor();
    processor.processXSL(xsl,xml,out);
    Any advice appreciated.

  • XML stream and stored as an output XML file

    Dear ALL,
    Could you help me in such situation?
    I need create XML file. I have DTD file. I create XML stream and stored as an output XML file. But all the data of my XML file stored in one line.
    How I can create my XML file according to DTD file?
    Thanks a lot.
    Best regards,
    Igor

    hi
    good
    go through this links,hope these would help you to solve your problem
    http://rustemsoft.com/JSPsample.htm
    http://publib.boulder.ibm.com/infocenter/wsphelp/index.jsp?topic=/com.ibm.etools.xmlbuilder.doc/tasks/txmltask.htm
    thanks
    mrutyun^

  • Java Input and Output streams

    I have maybe simple question, but I can`t really understand how to figure out this problem.
    I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
    from mobile phone:
    out.writeUTF("GETIMAGE")
    getImage();
    form computer:
    reply = in.readUTF();
    if(reply.equals("GETIMAGE")) sendimage()
    But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
    Please explain how to correcly solve such problem?
    Thanks,
    Ervins

    Eh?
    TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
    Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
    int type = dataInputStream.read();
    int length = dataInputStream.readInt();
    byte[] buffer = new byte[length];
    int count, read = 0;
    while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
    read += count;
    // At this point we either have:
    // type == -1 || count = -1 => EOF
    // or count > 0, type >= 0, and buffer contains the entire packet.
    switch (type)
    case -1:
    // EOF, not shown
    break;
    case COMMAND: // assuming a manifest constant somewhere
    // process incoming command
    break;
    case IMAGE:
    // process or continue to process incoming image
    break;
    }No threads, no polling, and nuthin' up my sleeve.
    Modulo bugs.

  • Java Sockets and Output Streams

    Hi All,
    I am beginning sockets programming and I have a problem. If there is a server listening in the background for incoming connections and say for example 4 client programs programs which we shall call client1...client4 connect. How best can I capture the output streams associated with these newly created sockets so that the server can send back isome nformation to say clients1 and client4 only which is not seen by clients 2 and 3. Similarly I would like the server to send some infor to clients 2 and 3 only which is not seen by client1 and client 4.
    Currently I have the server listening part as shown below, but not too sure how to add DISTINCT output streams for 1 and 4 on one hand and 2 and 3 on the other.
    Thanks:
    // bind socket to a port number
    ServerSocket serverSocket = new ServerSocket(portNo);
    // create socket to listen to client connection
    while (true) {
    //listen to an incoming connection
    System.out.println("chatroom server waiting for incoming connections");
    Socket incomingSocket = serverSocket.accept();
    //launch new thread to take care of new connection
    chatRoomThread chatThread = new chatRoomThread(incomingSocket);
    chatThread.start();
    //go back and wait for next connection
    Please help.
    Thanks,
    Bleak

    HouseofHunger wrote:
    yes thats exactly the way I have my in and out streams, in the run method, but that doesn't help me in filtering traffic, in other words I am saying 2 clients, client1 and client4 for example should share a common in and out stream so that they will see eact other's messages... makes sense.....?No, doesn't make sense. That's the wrong design. Each socket should have its own input and output stream (yes, I know, that's been said several times before). If messages going to client1 should also be sent to client4, then whatever writes the messages to client1's output stream must also write them to client4's output stream. Trying to make those two output streams actually be the same output stream is the wrong way to do that. Just have the controller send the messages to whoever is supposed to get them.

  • Create XML stream and stored as an output XML file

    Dear ALL,
    Could you help me in such situation?
    I need create XML file. I have DTD file. I create XML stream and stored as an output XML file. But all the data of my XML file stored in one line.
    How I can create my XML file according to DTD file?
    Thanks a lot.
    Best regards,
    Igor

    hi
    good
    go through this links,hope these would help you to solve your problem
    http://rustemsoft.com/JSPsample.htm
    http://publib.boulder.ibm.com/infocenter/wsphelp/index.jsp?topic=/com.ibm.etools.xmlbuilder.doc/tasks/txmltask.htm
    thanks
    mrutyun^

Maybe you are looking for

  • Log and capture freezes - please help

    hi, I'm using FCP 5 (studio). on G5 dual 2GH 1GB. it has become a nightmare to log and capture. after few minutes from working with log and capture the applications freezes. I have to force quit FCP. I trashed the preferences once, I re-installed, bu

  • Problems with dvd-drive

    Hi. I have a Lite-on cd/dvd-drive, which writes and reads discs. About a week ago i tried to burn a dvd, and noticed that my drive is not detected by Brasero. I tried other programs, and same thing with them (gnomebaker detected my drive, but it did

  • Distorted images in Slideshow

    I have a website that I'm working on, and I put some images in a thumbnail slideshow. All of the colors are messed up? Any help? Thanks, Andrew

  • ODI Procedure (passing parameter from command on source to command on target) issue.

    Hi All, I am working on ODI 11.1.1.5. I am trying to run a select query on 'command on source' and tying to capture the output into command on target and execute the code captured. 'command on source' select 'BEGIN ' || 'dbms_stats.gather_table_stats

  • Can't exit pdf file in internet explorer.

    When I open a pdf file in internet explorer, I an unable to exit the pdf file.  The only way I can get out of it is by shutting down internet explorer.  I am using internet explorer 11 with windows 7.  Is there a way to resolve this issue??