Usage of BufferedInputStream & OutputStream#flush()

I have a snippet below.
InputStream fileInputStream = formFile.getInputStream();//org.apache.struts.upload.FormFile
OutputStream out = = new BufferedOutputStream(new FileOutputStream(tempFilePath));
byte[] buffer = new byte[256 * 1024];
int contentLength;
while ((contentLength = fileInputStream.read(buffer)) > 0) {
out.write(buffer, 0, contentLength);
out.close();
fileInputStream.close();1. Should I use BufferedInputStream wrapping around formFile.getInputStream() ? I upload huge size files, say > 500 MB.
2. Should I really call out.flush() somewhere ? If yes, should it be inside while loop or after while loop ?
thanks in advance.

baskark wrote:
Otherwise, there's no need to call it. If you're already done writing, you'll call close(), and that will call flush() anyway. If you're writing all of the data in chunks one right after the other, and not stopping to do other processing between chunks, then you'll be writing as fast as possible and calling close() right away anyway, so, again, no benefit to calling flush.Will calling flush() before calling next write() make a difference in performance ?Calling flush unnecessarily could potentially slow things down, but you'd probably have to do a lot of it to be noticeable.
Also using BufferedInputStream wrapping around formFile.getInputStream() improves performance in anyway ?If you're reading in large chunks with read(byte[]), it probably won't make a difference. But if you're reading into a very small byte array, or reading one byte at a time with read(), then using the BufferedInputStream will be baster.

Similar Messages

  • The contract for java.io.OutputStream.flush()

    The Javadoc for method java.io.OutputStream.flush() is
    public void flush()
               throws IOException
        Flushes this output stream and forces any buffered output bytes to be written out. The
    general contract of flush is that calling it is an indication that, if any bytes previously
    written have been buffered by the implementation of the output stream, such bytes
    should immediately be written to their intended destination.Thread http://forums.sun.com/thread.jspa?threadID=5318876&tstart=0 highlighted a problem with this contract in that there are some OutputStream such as CipherOutputStream (when using PKCS5Padding) where it does not make sense to implement to the flush() contract. In meeting this contract one would have to close the stream so that nothing else could be written after a flush. The reason for the problem is that only complete blocks of data can be written. Until one has a complete block, the bytes of an incomplete block have to be stored in the CipherOutputStream. Only when one closes a CipherOutputStream can the bytes of the incomplete block be padded to create a complete block, encrypted and then written.
    I have a similar problem with my Base64OutputStream where I can only write a multiple of 3 input bytes until I close() when I can provide appropriate padding.
    So, should one do as ghstark proposed in http://forums.sun.com/thread.jspa?threadID=5318876&tstart=0 and close() the stream when one flushes it or should one do as I currently do and only write out as much as possible without closing the stream. It would seem that one either has to break the flush() contract or break the encryption (or in my case Base64) contract.
    I would appreciate comments.

    DrClap wrote:
    Well, if it were me I would probably redefine the flush() method to only write the bytes that I was ready to write. So in your Base64 case I might be holding back one or two bytes.That is exactly what my Base64OutputStream and Sun's CipherOutputStream do.
    If challenged on that I would just say that my flush() method conformed to the contract because those bytes weren't "buffered" yet.I like the concept but any wording would have to be carefully written. I suppose that I could argue that I have not buffered any bytes that could be written so I have not buffered any bytes.

  • Activity usage will be back flushed at target

    How can I confirm activity usage by back flushing target quantities based on actual quantity delivered into stock from a process order?
    Could you please advise how we can do the above?
    Currently we are confirming the activity based on the planned hrs. But how could it be possible in SAP to Confirm the activity usage based on the delivered stock from a process order
    The above is only relevant to Activity but not component materials.
    Thank you

    hi,
    Use t.code CO11N for activity confirmation.
    thx,
    Ganu

  • BufferedInputStream / OutputStream Help

    My File I/O program is up and running fine, but when I copy a text file to another location it adds a few more characters to the end of the file.
    File fileF = new File( "H:\Java_Projects\db.rtf" );
    File newFile = new File( H:"\Java_Projects\db2.rtf" );
    //db2.rtf does not exist yet
    BufferedInputStream bufIn = new BufferedInputStream( new FileInputStream( fileF ) );
    BufferedOutputStream bufOut = new BufferedOutputStream ( new FileOutputStream( newFile ) );
    int check;
    byte [] buff = new byte[128];
    while( ( check = bufIn.read( buff, 0, 128 ) ) != -1 ) {
    bufOut.write( buff, 0, 128 );
    bufOut.flush();
    This code will copy any file type that you specify, but with long text files I get xtra characters at the very end.
    Anybody know how to fix this? Thx!!

    I'd replace this --
    bufOut.write( buff, 0, 128 );with this --
    bufOut.write( buff, 0, check );kind regards,
    Jos

  • When to use BufferedInputStream/OutputStream/Reader/Writer

    I'd be very grateful if someone could explain when to use BufferedInputStream, etc., and what the dis/advantages are.
    TIA
    Shaun

    data channels such as files sockets, etc, tend to be
    a) slow
    b) block oriented
    BufferedOutputStream attempts to mitigate this by presenting data in block format. Rather than a bunch of little segments of bytes.

  • Need help with applet servlet communication .. not able to get OutputStream

    i am facing problem with applet and servlet communication. i need to send few image files from my applet to the servlet to save those images in DB.
    i need help with sending image data to my servlet.
    below is my sample program which i am trying.
    java source code which i am using in my applet ..
    public class Test {
        public static void main(String argv[]) {
            try {
                    URL serverURL = new URL("http://localhost:8084/uploadApp/TestServlet");
                    URLConnection connection = serverURL.openConnection();
                    Intermediate value=new Intermediate();
                    value.setUserId("user123");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setDefaultUseCaches(false);
                    // Specify the content type that we will send binary data
                    connection.setRequestProperty ("Content-Type", "application/octet-stream");
                    ObjectOutputStream outputStream = new ObjectOutputStream(connection.getOutputStream());
                    outputStream.writeObject(value);
                    outputStream.flush();
                    outputStream.close();
                } catch (MalformedURLException ex) {
                    System.out.println(ex.getMessage());
                }  catch (IOException ex) {
                        System.out.println(ex.getMessage());
    }servlet code here ..
    public class TestServlet extends HttpServlet {
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             System.out.println(" in servlet -----------");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ObjectInputStream inputFromApplet = null;
            Intermediate aStudent = null;
            BufferedReader inTest = null;
            try {         
                // get an input stream from the applet
                inputFromApplet = new ObjectInputStream(request.getInputStream());
                // read the serialized object data from applet
                data = (Intermediate) inputFromApplet.readObject();
                System.out.println("userid in servlet -----------"+ data.getUserId());
                inputFromApplet.close();
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("WARNING! filename.path JNDI not found");
            } finally {
                out.close();
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in foGet -----------");
            processRequest(request, response);
         * Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            System.out.println(" in doPost -----------");
            processRequest(request, response);
         * Returns a short description of the servlet.
         * @return a String containing servlet description
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    }the Intermediate class ..
    import java.io.Serializable;
    public class Intermediate implements Serializable{
    String userId;
        public String getUserId() {
            return userId;
        public void setUserId(String userId) {
            this.userId = userId;
    }

    Hi,
    well i am not able to get any value from connection.getOutputStream() and i doubt my applet is not able to hit the servlet. could you review my code and tell me if it has some bug somewhere. and more over i want to know how to send multiple file data from applet to servlet . i want some sample or example if possible.
    do share if you have any experience of this sort..
    Thanks.

  • Is there a way to flush out a socket's output stream without...

    ...having to close it (the stream)?
    I'm trying to implement a keep-alive feature in a simple HTTP Server application. This is a draft of the code I have trouble with:
    ==========
    //'clientSocket' is the socket obtained by the 'serverSocket.accept()' method
    OutputStream out = clientSocket.getOutputStream();
    //'message' is a string to be sent to the client
    InputStream data = new ByteArrayInputStream(message.getBytes());
    byte[] buff = new byte[2048];
    while (true)
    int read = data.read(buff, 0, 2048);
    if (read <= 0)
    break;
    out.write(buff, 0, read);
    out.flush();
    ==========
    If I don't call 'out.close()', the data will not be sent to the client.
    If I call 'out.close()', the data will be sent, but the socket will be closed too, which I don't want to. I need to be able to reuse that socket .
    Is there any way to properly push out the data to the client without having to close the output stream?

    ...having to close it (the stream)?Yes. OutputStream.flush(). But if you're not using any kind of buffered writer/output stream you don't even have to do that.
    If I don't call 'out.close()', the data will not be sent to the client.Untrue. The client will read everything that has been written If you don't close the output stream, the client will never get the EOS indication (e.g. read() returning -1). So if your client is looping until that happens it will loop forever ...
    Your problem at the moment is at the reading end.

  • OutputStream Losing session Data

    i have a jsf adf 11 project where i have a jspx page with two graphs.
    and i have a button where clients make a download the graph image.
    FacesContext fctx = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fctx
    .getExternalContext().getResponse();
    response.reset();
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Refresh", "1");
    response.setContentType("application/png");
    response.setHeader("Content-disposition", "attachment; filename=teste.png");
    try {           
    OutputStream outputStream = response.getOutputStream();
    graphSexo.getImageView().exportToPNG(outputStream);
    outputStream.flush();
    } catch (Exception e) {
    e.printStackTrace();
    fctx.responseComplete();
    My problem is after download prompt displays to the client, i lose all data from the page !
    I need to reder this page again to another download of this image !
    can anyone help me!?
    sorry about my english !!!

    I think you are using IE6 plus SP1. If yes try uninstall SP1 and you should be able to run an application as expected. I just had experienced "lost session" on WebSphere 4(WS4) with IE6+SP1 so I tested IE6+SP1(with varity of configuration setting) with WS on all SP of WS -> still lost the session. But testing IE6+SP1 on another application servers, I just tried couple of them but it all work fine. I finally test IE6 without SP1 -> the session is worked fine with the same application that didn't work on IE6+SP1.
    Guess it is the conflict between WS and IE6+SP1
    hope this helps.

  • Getting error while opening pdf on server

    Dear All,
    I am working on jdeveloper 11.1.1.4.0.
    I have a use case where on click of link , generating a dynamic pdf. The pdf i am arranging with the help of itext through backing bean. It is generating as well downloading the pdf.I have used filedownloadlistner to call the generate and download pdf methods.
    On integrated weblogic server the pdf is working fine, but when i deploy on server while opening pdf getting error :
    *"Adobe Reader could not open 'test.pdf' beacause it is either not a supported file type*
    *or because the file has been damaged (for example, it was sent as an email attachment and*
    *wasn't correctly decoded)."*
    I am not able to get the root cause for the problem. The sample code to generate and download pdf is :
    // Generate PDF
    private void generatePDFFile(FacesContext facesContext,
    java.io.OutputStream outputStream) {
    try {
    System.out.println("In Generate PDF................");
    Document document = new Document(PageSize.A4);
    PdfWriter.getInstance(document, new FileOutputStream(FILE));
    document.open();
    addMetaData(document);
    addTitlePage(document);
    document.close();
    System.out.println("End of PDF......................");
    facesContext = facesContext.getCurrentInstance();
    ServletContext context = (ServletContext)facesContext.getExternalContext().getContext();
    System.out.println(context.getRealPath("/"));
    String FILE = "test.pdf";
    File file = new File(FILE);
    FileInputStream fdownload;
    //BufferedInputStream bis;
    byte[] b;
    System.out.println(file.getCanonicalPath());
    System.out.println(file.getAbsolutePath());
    fdownload = new FileInputStream(file);
    int n;
    while ((n = fdownload.available()) > 0) {
    b = new byte[n];
    int result = fdownload.read(b);
    outputStream.write(b, 0, b.length);
    if (result == -1)
    break;
    outputStream.flush();
    } catch (Exception e) {
    e.printStackTrace();
    Download PDF
    private void downloadPDF(FacesContext facesContext, java.io.OutputStream outputStream) {
    try {
    facesContext = facesContext.getCurrentInstance();
    ServletContext context = (ServletContext)facesContext.getExternalContext().getContext();
    ExternalContext ctx = facesContext.getExternalContext();
    HttpServletResponse res = (HttpServletResponse)ctx.getResponse();
    res.setContentType("application/pdf");
    outputStream = res.getOutputStream();
    System.out.println(context.getRealPath("/"));
    File file = new File(FILE); // FILE = 'test.pdf'
    FileInputStream fdownload;
    // BufferedInputStream bis;
    byte[] b;
    fdownload = new FileInputStream(file);
    //bis = new BufferedInputStream (new FileInputStream(file));
    int n;
    while ((n = fdownload.available()) > 0) {
    b = new byte[n];
    int result = fdownload.read(b);
    //outputStream.write(b, 0, b.length);
    outputStream.write(b, 0, b.length);
    if (result == -1)
    break;
    outputStream.flush();
    outputStream.close();
    fdownload.close();
    } catch (Exception e) {
    e.printStackTrace();
    Any help will be appreciated.
    Thanks
    Kanika

    If the pdf file don't open on the server where you created them, they won't open on the client side either.
    The code you are using should be refactored to use different file names for the generated files. In a multi user environment (which every web application is) you overwrite the file generated with each new request, even before the file is loaded by a client. This will corrupt the file a client is loading and you get the error you see.
    Next I would look into org.apache.commons.io package (http://commons.apache.org/io/) which has utility classes which allows easy handling of streams without looping over the data.
    Timo

  • Java.io.StreamCorruptedException: InputStream does not contain a serialized object

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

  • Problem file xls with jasper (source code mixed in the content XLS file)

    i´m writing xls file with jasper, the problem is that is mixed the source code of the JSP (where doing request) in the content of the file xls, do not import the API thah use.
    The java code whit JASPER is like:
    FacesContext ctx = FacesContext.getCurrentInstance();
    ExternalContext ectx = ctx.getExternalContext();
    JRDataSource dataSource = ......
    InputStream inputStream = ectx.getResourceAsStream(parametro);
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inputStream);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,new HashMap(), dataSource);
    JRXlsExporter exporter = new JRXlsExporter();
    ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, xlsReport);
    exporter.exportReport();
    byte[] bytes2 = xlsReport.toByteArray();
    response.setContentType("application/vnd.ms-excel");
    response.setContentLength(bytes2.length);
    response.setHeader("Content-disposition", "attachment; filename="" + "MI_EXCEL_JR" + ".xls"");
    ServletOutputStream outputStream = response.getOutputStream();
    outputStream.write(bytes2, 0, bytes2.length);
    outputStream.flush();
    outputStream.close(); whay is printed the response in the xml file?
    tnk for your help....

    hoham wrote:
    byte[] bytes2 = xlsReport.toByteArray();
    Not related to the actual problem, but this line is not very efficient. What if the report is bigger than the available server memory? Or if there are many simultaneous requests which does all the same?
    It would result in an OutOfMemoryError. Rather obtain it as an InputStream and write it in a loop to the OutputStream using a byte block as buffer. Or wrap the both streams by BufferedInputStream/BufferedOutputStream and write in a simple loop. Consult the basic Java IO tutorials for details and code examples.

  • Bad performance in LAN

    Hi
    I use BufferedInputStream and BufferedOutputStream to implement a specific JDBC driver for my middleware-basd database. It runs well until recently the system admins of my school upgrade the operation system (Redhat). Before the upgrade, the roundtrip time is only less than 5 ms in LAN. But after the upgrade, the roundtrip time goes beyond 30ms, even if the client and the server sockets are in the same machine.
    I debugged it carefully. It seems that the sometimes inputStream.read() takes about 30ms, but sometimes it only takes 0-1 ms. I doubt that it is due to buffer size (I use 8192 for input and output)and the stream is not flush immediately. But even after I add outputStream.flush() in the server side, there is still the same problem.
    I asked the system admin to change the operation system back to the original version. And the socket performance is fine.
    I even tried a AF_UNIX socket (java codes based on JNI and C) between client and server in the same machine. Even with the new operation system, the performance is also good.
    Can any experts give any suggestions?
    thanks in advance.

    With a middleware system there would typically be at least three boxes involved.
    client, middleware server, database.
    So which box was updated?
    Was DNS running on the updated box by chance?
    And did you verify that the update did not change the version of java that was being run?

  • Down excel file in managed bean, no response?

    Hi,
    I used JDev 11.1.2
    I want to download an excel file by click one button, and I want to implement this function in the managed bean, but after I click the button, no file download, and just refresh the page.
    JSP snippet code:
    <af:commandToolbarButton text="View Report" id="ctb1" actionListener="#{reportBean.viewReport}">
    Method of managed bean(not show exception process ):
    public void viewReport(ActionEvent actionEvent) {
    // some validation here
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse)externalContext.getResponse();
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    String filePath = "c:/a.xls";
    File file = new File(filePath);
    try {
    input = new BufferedInputStream(new FileInputStream(file), 1024);
    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filePath + "\"");
    response.setContentType("application/ms-excel");
    output = new BufferedOutputStream(response.getOutputStream(), 10240);
    byte[] buffer = new byte[10240];
    int length;
    while ((length = input.read(buffer)) > 0) {
    output.write(buffer, 0, length);
    output.flush();
    }catch(Exception e){
    } finally {
    //close output and input
    facesContext.responseComplete();
    BTW: I can implement the download function by using fileDownloadActionListener, but our requirement needs to validate some information before download(such as status validation, file existence), and I add those validation to fileDownloadActionListener method, but seems no useful.
    Any advices?
    Thanks,
    zeroxin

    Timo,
    I used the solution mentioned in your blog, and it really can enter into fileDownloadActionListener method, but still not display download file dialog, just seems no useful, I test it using Firefox4 and IE9, the same result.
    JSP snippet code:
    <af:commandToolbarButton text="View Report" id="ctb1"
    actionListener="#{reportBean.viewReport}"/>
    <af:commandToolbarButton text="Export..." id="ctb2" visible="false"
    binding="#{reportBean.exportReportButton}">
    <af:fileDownloadActionListener contentType="application/vnd.ms-excel" filename="Report.xls" method="#{reportBean.reportFileDownload}" />
    </af:commandToolbarButton>
    Bean method(Snippet code)
    private RichCommandToolbarButton exportReportButton;
    public void viewReport(ActionEvent actionEvent) {
    // validate code here
    ActionEvent ae = new ActionEvent(exportReportButton);
    ae.queue();
    public void reportFileDownload(FacesContext facesContext, java.io.OutputStream outputStream) throws Exception {
    DCIteratorBinding dciter = (DCIteratorBinding)getBindings().get("SReportView1Iterator");
    Object outputLoc = dciter.getCurrentRow().getAttribute("OutputLoc");
    BufferedInputStream input = null;
    try {
    input = new BufferedInputStream(new FileInputStream((String)outputLoc), 1024);
    byte[] buf = new byte[1024];
    int count=0;
    while ((count = input.read(buf)) >= 0) {
    outputStream.write(buf, 0, count);
    input.close();
    outputStream.flush();
    outputStream.close();
    } catch (Exception e) {
    e.printStackTrace();
    thanks,
    zeroxin

  • PDF does not show up

    Hi all,
    The following is my code snippet in JSP for a project which i used to generate a PDF file. But the PDF does not show up . The Adobe loads and i get a pop-up saying
    'Acrobat could not open 'Example[1].pdf' because it is either not a supported file type or because the file has been corrupted.'
    This is the code snippet i used:
    <%@ page import="java.io.*" %>
    <%
    String s = new String("Hai this is PDF Sample");
    byte file[] = s.getBytes();
    try
    BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(file));
    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
    response.setHeader ("Content-Disposition", "attachment; filename=Example.pdf");
    response.setContentType("application/pdf ; charset=iso-8859-1");
    int bytes = 0;
    byte buffer[] = new byte[1024];
    while((bytes = inputStream.read(buffer)) != -1)
    outputStream.write(buffer,0,bytes);
    inputStream.close();
    outputStream.flush();
    outputStream.close();
    }catch
    (Exception e){}
    %>
    Can anyone please help me out.
    Thanks in Advance.
    RDP.

    FOP is an Apache project that lets you generate PDFs using XML and XSL.
    Here's the servlet:
    package common.servlets;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.StringReader;
    import java.net.URLDecoder;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXResult;
    import javax.xml.transform.stream.StreamSource;
    import org.apache.fop.apps.Driver;
    * A servlet that takes XML and XSL streams and sends back a PDF file,
    * using Xalan and FOP.
    public class PDFServlet extends HttpServlet
        /** Response content type */
        public static final String DEFAULT_RESPONSE_CONTENT = "application/pdf";
        /** Parameter/attribute name for XML input */
        public static final String DEFAULT_XML_NAME = "print.xml";
        /** Parameter/attribute name for XSL input */
        public static final String DEFAULT_XSL_NAME = "print.xsl";
        /** Default character encoding */
        public static final String DEFAULT_CHAR_ENCODING = "UTF-8";
        /** Transformation factory */
        private TransformerFactory transformerFactory;
         * Initialize the servlet
         * @throws ServletException if the initialization fails
        public void init() throws ServletException
            try
                this.transformerFactory = TransformerFactory.newInstance();
            catch (Exception e)
                throw new ServletException(e);
         *  Process a GET request
         * @param servlet request
         * @param servlet response
         * @throws ServletException if the servlet fails
         * @throws IOException if IO fails
        public void doGet(HttpServletRequest request,
                                     HttpServletResponse response)
            throws ServletException, IOException
            this.doPost(request, response);
         * Process a POST request by looking up the JSP using the source + action
         * parameters
         * @param servlet request
         * @param servlet response
         * @throws ServletException if the servlet fails
         * @throws IOException if IO fails
        public void doPost(HttpServletRequest request,
                           HttpServletResponse response)
            throws ServletException, IOException
            try
                Driver driver = new Driver();
                driver.setRenderer(Driver.RENDER_PDF);
                ByteArrayOutputStream baos  = new ByteArrayOutputStream();
                driver.setOutputStream(baos);
                Map parameters   = request.getParameterMap();
                String xmlString = null;
                if (parameters.containsKey(DEFAULT_XML_NAME))
                    xmlString = request.getParameter(DEFAULT_XML_NAME);
                else
                    xmlString = (String)request.getAttribute(DEFAULT_XML_NAME);
                String xslString = null;
                if (parameters.containsKey(DEFAULT_XSL_NAME))
                    xslString = request.getParameter(DEFAULT_XSL_NAME);
                else
                    xslString = (String)request.getAttribute(DEFAULT_XSL_NAME);
                if ((xmlString != null) && (xslString != null))
                    xmlString = URLDecoder.decode(xmlString, DEFAULT_CHAR_ENCODING);
                    xslString = URLDecoder.decode(xslString, DEFAULT_CHAR_ENCODING);
                    Source xml = new StreamSource(new StringReader(xmlString));
                    Source xsl = new StreamSource(new StringReader(xslString));
                    Result fop = new SAXResult(driver.getContentHandler()); // Intermediate result
                    Transformer transformer = this.transformerFactory.newTransformer(xsl);
                    transformer.transform(xml, fop);
                    response.setContentType(DEFAULT_RESPONSE_CONTENT);
                    response.setContentLength(baos.size());
                    response.getOutputStream().write(baos.toByteArray());
                    response.getOutputStream().flush();
                else
                    PrintWriter out = response.getWriter();
                    if (xmlString == null)
                        out.println("Missing XML");
                    if (xslString == null)
                        out.println("Missing XSL");
            catch (TransformerException e)
                e.printStackTrace(System.err);
                throw new ServletException(e);

  • Http Request never ends

    Hi,
    Well I had a few minutes on my hand and decided to build a simple socket application that handles a browser request with a �hello�. Then I decided to complicate that a little and to actually send back what I receive. However the while loop that checked the input from the browser never ends (that is I never get a �1 from inputStream.read() method).
    Could someone please explain me why this happens? And how this could be solved? I mean how to detect that the request is over and it is time to respond. (In other words how can I base my response according to the request if I never know when the request is over!).
    Here is the code I used import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Test7 {
    public static void main(String[] args) {
      try {
       ServerSocket serverSocket = new ServerSocket(9989);
       while(true){
        Socket socket = serverSocket.accept();
        new Thread(new SimpleHttpHandler(socket)).run();
      catch (Exception e) {
       e.printStackTrace();
    class SimpleHttpHandler implements Runnable{
    private Socket client;
    public SimpleHttpHandler(Socket client){
      this.client = client;
    public void run(){
      try{
       BufferedOutputStream outputStream = new BufferedOutputStream(
         this.client.getOutputStream()
       BufferedInputStream inputStream = new BufferedInputStream(
         this.client.getInputStream()
       int in = 0;
       while((in = inputStream.read()) != -1){
        System.out.print((char)in);
        outputStream.write(in);
       outputStream.close();
       outputStream.flush();
      catch(Exception e){
       e.printStackTrace();
    Regards,
    Sim085

    So you can't read RFC but can read forums? :)Can you imagine reading documentation about something by continuously minimizing and maximizing the browser window? (which I do when at work so to attract less attention) :)
    Well if you want simplest way then just send header,
    data and close connection that's enough.Thanks :) I understand that now :)
    @bsamperi & [email protected]
    The code I provided above was not correct. I fixed it and posted it again just in case someone else comes across this post. As already said this was not what I had in mind to do in the first place, but it was fun :) Anyways here is the working code! (Although naturally not good for anything)import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Test7 {
    public static void main(String[] args) {
      try {
       ServerSocket serverSocket = new ServerSocket(8871);
       while(true){
        System.out.println("Waiting for request");
        Socket socket = serverSocket.accept();
        new Thread(new SimpleHttpHandler(socket)).run();
      catch (Exception e) {
       e.printStackTrace();
    class SimpleHttpHandler implements Runnable{
    private final static String CLRF = "\r\n";
    private Socket client;
    private BufferedWriter writer;
    private BufferedReader reader;
    public SimpleHttpHandler(Socket client){
      this.client = client;
    public void run(){
      try{
       this.writer = new BufferedWriter(
         new OutputStreamWriter(
           this.client.getOutputStream()
       this.reader = new BufferedReader(
         new InputStreamReader(
           this.client.getInputStream()
       System.out.println("-- IN --\n" + this.read() + "\n");
       System.out.println("-- OUT --\n" + this.write("Thank You"));
       this.writer.close();
       this.reader.close();
       this.client.close();
       System.out.println("Completed response");
       System.out.println("--------------------\n");
      catch(Exception e){
       e.printStackTrace();
    private String read() throws IOException{
      String in = "";
      StringBuffer buffer = new StringBuffer();
      while(!(in = this.reader.readLine()).trim().equals("")){
       buffer.append(in + "\n");
      return buffer.toString();
    private String write(String out) throws IOException{
      StringBuffer buffer = new StringBuffer();   
      buffer.append("HTTP/1.0 200 OK" + CLRF);
      buffer.append("Content-Type: text/html" + CLRF);
      buffer.append(CLRF);
      buffer.append(out);
      buffer.append(CLRF);  
      writer.write(buffer.toString());
      return buffer.toString();
    }The output of this code is: Waiting for request
    -- IN --
    GET / HTTP/1.1
    Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
    application/vnd.ms-powerpoint, application/vnd.ms-excel,
    application/msword, application/x-shockwave-flash, */*
    Accept-Language: en-us
    UA-CPU: x86
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2;
    .NET CLR 1.1.4322; .NET CLR 2.0.50727)
    Host: localhost:8871
    Connection: Keep-Alive
    -- OUT --
    HTTP/1.0 200 OK
    Content-Type: text/html
    Thank You
    Completed response
    Waiting for request
    -- IN --
    GET /favicon.ico HTTP/1.1
    Accept: */*
    UA-CPU: x86
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2;
    .NET CLR 1.1.4322; .NET CLR 2.0.50727)
    Host: localhost:8871
    Connection: Keep-Alive
    -- OUT --
    HTTP/1.0 200 OK
    Content-Type: text/html
    Thank You
    Completed response
    Waiting for request
    ...Which shows that this application will handle any web request with a �Thank You� since I am not basing the response on the request. However that should not be hard once the request and response are handled ok.
    Thank to both of you for your help :)
    Regards,
    Sim085

Maybe you are looking for

  • Multiple tables feeding one table

    Hi All, What is the best method to feed data one central table with data from multiple other tables? Here is the scenerio/requirement: >BI Query 1 --> VC Table 1 --| >.........................................| >BI Query 2 --> VC Table 2 --| >........

  • Problem in sending a attachnment or photo using javamailapi

    Hello Sir, My program is perfectly when i'm sending simply a text message but problem is arised when i want to send an attachment. MY Code is import javax.mail.*; import javax.mail.internet.*; import java.util.*; import java.io.*; import javax.activa

  • What are all the possible AIA faults?

    Hi all, I need to know what are all the possible AIA faults apart from the system faults provided by the SOA Suite. whether AIA faults are completely different from the system faults of soa suite?. I haven't found any specifically named AIA faults in

  • Disabling selection of JSeparator in a JComboBox

    Does anyone know how to disable the selection of a JSeparator in a JComboBox? I'm using JRE 1.1.8.

  • GI/GR from Pi sheet

    Dear All, I am using the following INSTRUCTION for Material list in PI sheet. ZMATINF - 10 PPPI_MATERIAL 20 PPPI_RESERVATION_ITEM 30 PPPI_MATERIAL_SHORT_TEXT 40 PPPI_BATCH 50 PPPI_MATERIAL_QUANTITY 55 PPPI_MATERIAL_CONSUMED 60 PPPI_UNIT_OF_MEASURE 70