Write out file through servlet

Hello all,
I wish to write out a file when a servlet is requested; however the file may be quite large and take a couple of seconds (approx 10) to write out. This results in a ten second delay for the user. I wish to offset this delay so the servlet continues executing returning the response and the file is written out in some form of background process.
Could someone point me in the right direction?
Thanks
John

Write up a Thread class to do the file writing for you. Your servlet will only start the thread with the required arguments and will generate the response without waiting for the thread to complete.

Similar Messages

  • Write out file from java UDF?

    I have a synchronous RFC->XI->HTTP (no BPM) process and need to write out a log of the call details each time it runs.  At first, I tried having multiple receivers (one for HTTP and one for log file) in IB:Config, but received an error that I "cannot have multiple receivers when synchronous call".
    Should I be able to write out a file using java code in a UDF?  Should I do something with a BPM (and if so, any hints)?
    Thanks in advance!

    It deppends on which kind of log you want and how much time you're willing to spend on this.
    If you want to learn BPM and has available time to learn and implement, go for it. It will provide you more flexibility (since you can use any adapter protocol) and is way better for maintenance purposes.
    Your BPM will basically have 4 steps:
    1. A Receiver step in "Open S/A Bridge" mode;
    2. A Sender step in Asynchronous mode (to send the log message to your target system);
    3. A Sender step in Synchronous mode (to send the request to HTTP and receive the response);
    4. A Sender step in "Close S/A Bridge" mode.
    The mapping can be made in three ways:
    1. mapping between RFC and BPM (so your BPM will have abstract interfaces based on HTTP interface); or
    2. mapping between BPM and HTTP (so your BPM will have abstract interfaces based on RFC interface); or
    3. create 2 transformation steps in the BPM, one to map from RFC.request to HTTP.request and the other to map from HTTP.response to RFC.response (I'd not recomend this).
    Regards,
    Henrique.

  • Running an executable file through servlet

    Hello People,
    I tried searching about this on the Forums, but could not find the right solution.
    Please donot get annoyed if you find this to be a repeted topic, which I am sure is not.
    I want to run a .sh file in Unix environment through servlet.
    Actually i want to do this inorder to schedule a report servet to run a report and generate the output in a particular format on a click of a button.
    I tried using Runtime.getRuntime().exec method, (which I know through forum is unreliable)
    Can anyone suggest me a method through I can achieve this?
    Any suggestion is appreciated.
    Regards,
    Rohan Kamat

    Hi MOD,
    Thanks for the quick reply.
    Heres what I am doing to schedule.
    1) The client selects the necessary parameters from the front end and then saves it in a table.
    2) This he will be doing for as many reports as he wants, on an average there will be 200 reports daily.
    3) Once he has selected all the parameters for all the reports, he will go to the next screen and fire a script to run the reports at a time.
    4) This script will be fired only once. And once it is fired it will generate a PDF files of the reports.
    5) On the front end the screen will be refreshed showing the users the status of the reports that he has scheduled to be run
    I am using Servlets 2.0 version, and jdk.12
    Regards,
    Rohan Kamat

  • Streaming files through servlet

    Hi,
    I'm trying to stream a file to the client browser via a Struts action. I use a helper method as follows:
    public static void streamFile(HttpServletResponse response, String contentType, String fileName, InputStream fileData) throws Exception {
              response.setContentType(contentType);
              response.setHeader("Content-disposition", "attachment; filename=" + fileName);
              BufferedInputStream bis = null;
              BufferedOutputStream bos = null;
              OutputStream out = response.getOutputStream();
              try {     
                   bis = new BufferedInputStream(fileData);
                   bos = new BufferedOutputStream(out);
                   byte[] buff = new byte[2048];
                   int bytesRead;
                   //     Simple read/write loop.
                   while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                        bos.write(buff, 0, bytesRead);
              } catch (Exception e) {
                   throw new Exception("Could not stream file. Error: " + e.getMessage());
              } finally {
                   if (bis != null) {
                        bis.close();
                   if (bos != null) {
                        bos.close();
         }Here's the execute method code for my download action:
    InputStream is = new FileInputStream(new File("g:/Test.txt"));
              FileHelper.streamFile(response, "text/plain", "Test.txt", is);
              return null; "G:\Test.txt" is a valid file. When I tried to run the code, I got this error from the client:
    Internet Exporer cannot download download.do from 127.0.0.1. Internet Explorer was not able to open this site.
    The requested site is either unavailable or cannot be found. Please try again later.
    Any ideas what I'm missing here?
    Thanks in advance for any suggestions!

    Hi all,
    Have found out what's wrong with this.
    Seems like the struts contoller was set to use nocache="true" option, which causes problems because in order for files to be downloaded onto the client, caching must be enabled.
    This applies for all web application processes which need to download files onto the client.
    E.g., if you are using servlets/JSP, you need to make sure that you do not send the pragma=no-cache header.
    E.g. if you use a framework like Struts, you need to make sure that the framework does not disable caching for the module which handles the download.

  • How to get and display image file through servlet

    If I've got a jpg file on the server..
    How can I use servlet to return that image via the following calling method
    /displayfile?filename=image.jpg
    the image.jpg in the server will return
    I know that I need to set the content type to image/jpeg
    after that, how can I return the image file to browser?

    - Get the "file" Parameter from the URL QueryString
    - check if the File specified exists on your filesystem
    - read in the jpg from the file (best would be binary)
    - set the right Mime Type (as you already wrote)
    - write the filecontent to the ServletOutput as you would do with any other content
    - that's it.

  • How to properly write a CSV through Servlet?

    hi all
    i am writing an application which will
    write selected database records to a csv text file
    not getting how to start with a servlet?
    any help in this regard is appreciated.
    thanx

    Your thoughts are good but there are some issues with eachof those
    1. When I send back the Response to the old Browser with a JavaScript to popup a new Window, I have to re-render the original page again ... and that is a performance hole.
    2. The problem with popping up a window and posting to the servlet using Javascript is that I cannot do a server side validation of the post.
    Thanks

  • Please Help ! How would i Read xml file through servlet

    My requirement is that i have to make a stock exchange streamer.
    i am making an applet to show real time data to client. i had succeded in applet-servlet communication, but i m getting problem in
    parsing the xml files inside a servlet and throw it to applet again.

    I would suggest that you find out what the problem is, then. Once you find that out you will be far ahead of anybody else reading this post, because they have absolutely no idea what your problem is.

  • Problem in opening .ics and .vcs file types through servlet in IE browser.

    I'm having problem in downloading an .ics and .vcs file through servlet in I.E browser. It is happening fine in Mozilla firefox(they both are getting opened in OutLook), but in IE it says as undefined file type.
    I'm using Content Type as : 'text/Calendar' and then setting header as :
    response().setContentType("text/Calendar");
    response().setContentLength(file.length());
    response().setHeader("Content-Disposition", "attachment;
    filename="+filepath);
    and after that i'm writing it to OutPut stream.
    Plz Help.

    Hi,
    On page load check whether the session values are there. If not redirect the user to the login page.
    Hope this helps,
    Regards,
    Sammani

  • Write to file on server from app

    Am trying to write to a file on server from an application like this:
    java.net.URL url = new java.net.URL("http://www.rikif.dk/test.txt");
    URLConnection conn = url.openConnection();
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    PrintStream out =
    new PrintStream(conn.getOutputStream());
    out.print("sdfsdf");
    out.flush();
    out.close();
    But nothing happens. What am I doing wrong?

    No exceptions.. "Unlike other output streams, a PrintStream never throws an IOException".
    You can write a file through HTTP into a web server? It does not make sense really.. is the file writable in the web server?
    And why be writable - anyone would be able to write it then.
    You can achieve that through sockets. A java program on the remote machine (playing the role of a server) would accept data through a socket from the clients, and would write the files itself.. without need of web servers.
    You can use a tomcat server, and use a servlet, again to accept data and write the files itself.
    ..or?

  • RUNNING .SWF FILES THROUG SERVLET

    I WANT TO RUN THE .SWF(FLASH FILES) THROUGH SERVLET.IF ANYBODY HAS CODE PLEASE MAIL ME URGENTLY ON [email protected]

    you should be a little be more precise to tell us what you want to do.

  • How to write a file in unix server through oracle plsql code

    Hi All,
    My requirement is to create and write a file (any file for eg txt file) in unix box with in a specified directory through oracle plsql code.
    Oracle sits in windows server.
    using utl_file package we can create directory where oracle resides and write it there in oracle server in our case windows..
    But here we need to create,write a file but in unix server which is different server than where the oracle server resides..
    we are using Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    Can any one one please help me out in this issue...
    Thanks in Advance.
    Prakash

    Mr Prakash,
    Why are you asking this question multiple times in every forum you can spell?
    Valid responses have been presented to you already two times.
    Can you explain why you can't follow them up, but continue to abuse this forum by repeating doc questions?
    Sybrand Bakker
    Senior Oracle DBA

  • Write to existing file using servlets

    Every time I try to read an existing file using my current set of servlets, I get "File cannot be found". I don't understand what the problem is because I'm using the exact same location as the code where I read the document. Is there something else I'm missing? I've tried countless methods of writing, each will compile and such, but all give me the same result (IE nothing). Here's how my horrific code looks right now. Much was taken from the previous code that checks the passwords file.
    Technically, it compiles and runs, but I get "java.io.FileNotFoundException: \WEB-INF\passwords (The system cannot find the path specified)" in the output. The file IS THERE and can be read in my password checking servlet without a problem...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    public class passCheck extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            try {
                    String filename = "/WEB-INF/passwords";
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    String remember = request.getParameter("remember");
                    ServletContext context = getServletContext();
              FileOutputStream fos = new FileOutputStream(filename);
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            } // if (is != null)
                    else {
                    } // else (password not blank)
            finally {
                out.close();
            } // finally
    }

    OK... I feel a bit dumb now... This code was working earlier (the writing part) and now it's not working since I added in the username check portion. It should be essentially complete at this point, I just need to figure out why it no longer writes the file. Any clues or insights?
    I'm about to add a password checker (confirm both passwords entered on registration form are equal) Lets hope I don't mess more up...
    package hw3Pack;
    import java.io.*;
    import java.util.*;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import java.net.*;
    public class regComplete extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
            response.setContentType("text/html");
            HttpSession session = request.getSession(true);
            PrintWriter out = response.getWriter();
            boolean clear = true;
            try {
                    String email = request.getParameter("email");
                    String password = request.getParameter("password");
                    out.println(email +" and " + password);
                    String filename = "/WEB-INF/passwords";
                    ServletContext context = getServletContext();
                    InputStream is = context.getResourceAsStream(filename);
              if (!is.equals(null)) {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader reader = new BufferedReader(isr);
                   String text = "";
                            while ((text = reader.readLine()) != null) {              
                                    StringTokenizer st = new StringTokenizer(text, "," );
                                    String getEmail = st.nextToken();
                                    String getPass = st.nextToken();
                                            if (email.equals(getEmail) && !email.equals(null)) {
                                                    clear = false;
                                                    out.println("I'm sorry but that email address is in use.  Please try again.");
                                            } else {
                                            //do nothing
                    if (clear==true) {
                        File file = new File("/WEB-INF/passwords");
                        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
                        out.println("going");
                        writer.append("\r\n" +email +"," +password);
                        out.println("Writing");
                        writer.close();
                        } else {
                } // try
            finally {
                out.close();
                } // finally
      }

  • Processing a jsp file through a servlet first

    At my company we have a lot of code tied up in servlets for our website. We would like to integrate JSPs along side the servlet architecture. We need to process the html files though both our serlvet architecture (Our website menu system and security are handled here) and the jsp tags.
    Here is what currently happens. We write a webpage, the servlet archtecture process the pages, doing substitutions on specific objects and running code in specific objects to build the html that is sent to the users browser. Instead of immediately sending the output to the users browser, i'd like to process it through the jsp servlet first. How would I go about running the newly substituted code through the jsp engine?
    Thanks in advance,
    Jeff

    That I probably wasn't clear enough with what is happening on our site.
    Let me walk you through how our site works.
    Here is an extremely simple page, and i'll walk you through what happens.
    <HTML>
    <HEAD></HEAD
    <BODY>
    Welcome {!s:username!}
    <!--#SQLLOOP name="SELECT" QUERY="SELECT year, name FROM programs where program_group_id = 35"-->
    {!r:select:name!}--- {!r:select:year!}
    <!--#/SQLLOOP-->
    </BODY>
    </HTML>When that page is called, the servlet starts. It opens up the file, does a substitiution on {!s:username!} for the username variable from session data. It then will execute a javaclass for the SQLLLOOP statement and output the year and name for all values where the program_group_id = 35. After the substitutions are done, then spits the html back at you.
    Now what I would like to do is to get this code to play nice with JSPs.
    the <jsp:include> tag does not appear to work.

  • Generating pdf file through jsp/servlet

    One of the MIME types for servlets/JSP response is "application/pdf".
    After setting Content-Type header "application/pdf" in servlet by
    setContentType() method, I am unable to get the output in a pdf file.
    Please let me know how I can generate a pdf file through Servelt/JSP
    response.
    Thanks.

    We've got a product which allows you to convert XML to PDF from a JSP. It doesn't currently take straight HTML, but the XML syntax we use is pretty similar (you can use CSS2 and so on), so for many pages it doesn't take a lot of conversion.
    If you check out http://big.faceless.org/products/report/examples.jsp you'll see a few examples, two of which are dynamically run from a JSP. There's a free trial download for you to test with (although it's a commercial product).
    Hope that helps.
    Cheers... Mike
    Mike Bremford - CTO mike at big.faceless.org
    Big Faceless Organization http://big.faceless.org

  • Write file in servlet

    Hi all,
    I am developing an application but there is a error in my code i culdnt find so far. Can anyone help?
    I want to write to a .xml file in web server with servlet from remote. My code is
    private static String message = "Error during Servlet processing";
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    //        response.setContentType("text/html;charset=UTF-8");
            try {
                int len = request.getContentLength();
                byte[] input = new byte[len];
                ServletInputStream sin = request.getInputStream();
                int c, count = 0;
                while ((c = sin.read(input, count, input.length - count)) != -1) {
                    count += c;
                sin.close();
                String inString = new String(input);
                int index = inString.indexOf("/n");
                if (index == -1) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.getWriter().print(message);
                    response.getWriter().close();
                    return;
                String user = inString.substring(0, index);
                String data = inString.substring(index + 2);
                //decode application/x-www-form-urlencoded string
    //            String decodedUser = URLDecoder.decode(user, "UTF-8");
    //            String decodedData = URLDecoder.decode(data, "UTF-8");
    //            int i = decodedData.indexOf("/n");
    //            String user = decodedData.substring(0, i);
    //            String db = decodedData.substring(i + 2, decodedData.length());
                String result = "no";
    //            response.setContentType("text/html");
                String filename = "/WEB-INF/" + user + ".xml";
    //            String pathName = getServletContext (  ) .getRealPath ( "/" + filename ) ;
    //            String contentType = getServletContext (  ) .getMimeType ( pathName ) ;
    //            if  ( contentType != null ) 
    //                response.setContentType ( contentType ) ;
    //            else
    //                response.setContentType ( "application/octet-stream" ) ;
                try {
                    OutputStream fcheck = null;
                    byte[] buf = data.getBytes();
                    fcheck = new FileOutputStream(filename);
                    for (int i = 0; i < buf.length; i++) {
                        fcheck.write(buf);
    result = "yes";
    } catch (IOException ex) {
    Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
    result = "no";
    // ServletContext context = getServletContext();
    // set the response code and write the response data
    response.setStatus(HttpServletResponse.SC_OK);
    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    writer.write(result);
    writer.flush();
    writer.close();
    } catch (IOException e) {
    try {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter().print(e.getMessage());
    response.getWriter().close();
    } catch (IOException ioe) {
    ý am sending data from remote as a string and want to write it in xml. But it is not working. Where am i wrong?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I fixed it. But now it doesnt write to file and there is no error. So i cant find where am a wrong.
    I send a request, it is taking string but it is not writing to file eventhough it is entering the try block.
    Why it isnt writing? Is not servlet let it to write to file. My working code is here
    private static String message = "Error during Servlet processing";
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try {
                int len = request.getContentLength();
                byte[] input = new byte[len];
                ServletInputStream sin = request.getInputStream();
                int c, count = 0;
                while ((c = sin.read(input, count, input.length - count)) != -1) {
                    count += c;
                sin.close();
                String inString = new String(input);
                int index = inString.indexOf("/n");
                if (index == -1) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.getWriter().print(message);
                    response.getWriter().close();
                    return;
                String user = inString.substring(0, index);
                String data = inString.substring(index + 2);
                //decode application/x-www-form-urlencoded string
    //            String decodedUser = URLDecoder.decode(user, "UTF-8");
                String decodedData = URLDecoder.decode(data, "UTF-8");
    //            int i = decodedData.indexOf("/n");
    //            String user = decodedData.substring(0, i);
    //            String db = decodedData.substring(i + 2, decodedData.length());
                String result = "no";
                String filename = user + ".xml";
                try {
                    OutputStream fcheck = null;
                    byte[] buf = decodedData.getBytes();
                    fcheck = new FileOutputStream(filename);
                    for (int i = 0; i < buf.length; i++) {
                        fcheck.write(buf);
    // char buffer[]=new char[data.length()];
    // data.getChars(0, data.length(), buffer, 0);
    // FileWriter f0=new FileWriter(filename);
    // for(int i=0;i<buffer.length;i++){
    // f0.write(buffer[i]);
    result = "yes";
    } catch (IOException ex) {
    Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
    result = "no";
    // ServletContext context = getServletContext();
    // set the response code and write the response data
    response.setStatus(HttpServletResponse.SC_OK);
    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    writer.write(result);
    writer.flush();
    writer.close();
    } catch (IOException e) {
    try {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter().print(e.getMessage());
    response.getWriter().close();
    } catch (IOException ioe) {

Maybe you are looking for

  • Can I use a iTunes gift card to pay for 3G

    Thanks

  • Resource Bundle issue in ATG 10 migration

    Hi, Migrating from ATG 2007.1 to 10 & getting issues with resource bundle for Merchandizing pages in BCC.Page is loading the StoreMerchandisingIcons.swf from the WAR module.Additionally the page is throwing error #404 for StoreMerchandisingIcons_en.s

  • Just downloaded a new app; it said I was logged in on another device??

    I do have more than one iPod (I just got the new iPod 5), but I'd never downloaded this app before. It's called The Wizard of Oz Game. As soon as I opened it, it said I was logged in on another device and asked if I wanted to be logged out on that de

  • Market Basket Analysis

    Hi all, I am currently doing this course "Getting Started with MS Azure Machine Learning" by Buck Woody. One of the questions I have is How do I build a algorithm to develop a retail analytics solution? What retail data should I gather? My end object

  • Why is my IP Profile half of what it was?

    So I signed up for the 20mb broadband service and had it activated 14 days ago.  On the day it was activated, I ran a speed test and my IP profile was over 19,000Kbps (indeed, before I upgraded, BT told me from their data I would be achieving 19mb).