Reading Byte [] in JSP - Struts

Hi,
          I am storing PDF files as BLOB object in Oracle 9i Database.
          In my struts action class I am reading the file and converting it into byte [].
          I am storing this value in the session as an object and while reading in the JSP,I am getting only null.
          But when I check the size of the byte [], it says 7,which is the actual length.
          How to read the byte [] and put it session?
          Any suggestions.
          Regards,
          Ram

Hi Kris,
          Thank you for your inputs.
          I have tried this option also.
          Still I am getting the same issue like the "File does not begin with %PDF-".
          Actually I am getting the byte[] in my DAO class and passing that value to the action class by way of list.
          In my action class I am doing the below code.
          List lstResult = new ArrayList();
          byte[] byteArray = (byte[]) lstResult.get(0);
                         smCat.debug("DailySalesReportAction - b4 byte array");
                         // write data to output stream of response object
                         try {
                              st = objHttpResponse.getOutputStream();
                              smCat.debug("DailySalesReportAction - inside try");
                              objHttpResponse.setContentType("application/pdf");
                              objHttpResponse.setContentLength(byteArray.length);     
                              objHttpResponse.setHeader("Content-Disposition","inline");
                              st.write(byteArray);
                              st.flush();
                              st.close();
                         } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
          My DAO looks like this.
          public byte[] executeBlobQuery(String strQuery) {
                    java.sql.Connection vendorConn = null;
                         Blob blobResult = null;
                         int lob_length = 0;
                         BufferedInputStream bufferedInStream = null;
                         java.io.OutputStream os = null;
                         byte[] byteBuffer = null;
                         smCat.debug("Entering in executeBlobQuery DAO***************> ");
                         try {
                              try {
                                   mConnection = getConnection();
                              } catch (Exception e) {
                                   smCat.error(e.getMessage());
                              // Create a static JDBC statement
                              Statement m_stmt = mConnection.createStatement();
                              mConnection.setAutoCommit(false);
                              m_stmt.setFetchSize(10000);
                                                  ResultSet m_rs = m_stmt.executeQuery(strQuery);
                              // Increment the result set
                              if(m_rs.next()){
                              smCat.debug("strQuery "+strQuery);
                              //blobResult = ((OracleResultSet) m_rs).getBLOB("REPORT");
                              //blobResult = m_rs.getBlob("REPORT");
                              //byteBuffer = m_rs.getBytes("REPORT");
                              //System.out.println("Length is --> "+byteBuffer.length);
                              os = ((OracleThinBlob)blobResult).getBinaryOutputStream();
                              smCat.debug("Blob Retrived ");
                              //image = (oracle.sql.BLOB)m_rs.getBlob(1);
                              lob_length = (int) blobResult.length();
                              smCat.debug("Value is --> " + lob_length);
                              byteBuffer = new byte[lob_length];
                                             int length = -1;
                                             os.write(byteBuffer);
                              smCat.debug("Value of byteBuffer --> " + byteBuffer.length);
                                             os.flush();
                              mConnection.commit();
                                             os.close();
                              bufferedInStream =
                                   new BufferedInputStream(blobResult.getBinaryStream());
                              byteBuffer = new byte[lob_length];
                              bufferedInStream.read(byteBuffer, 0, lob_length);
                              bufferedInStream.close();
                         } catch (SQLException sqe) {
                              smCat.error(sqe.getMessage());
                         catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
          Ram

Similar Messages

  • Tracking a separate Thread  - java/jsp/struts

    Hi all,
    My project is a webapplication using java/jsp/struts. My requirement is to write bulk data to a file, which i want to run as a separate thread. Since it runs as a separate thread the control comes back to UI (userInterface) page. On subsequent request from UI page by the user i want to check whether the thread process is completed or not , so that i can read from the file. Is it possible to simultaneously read from the file when the thread is in the process of writing data to the file. If so any idea on how to implement this functionality in java?
    How to keep track of the separate thread (whether it is completed or not) in java?
    Is it possible to read from the file when the thread is writing to the file in java?
    Thanks is advance.

    dangerous wrote:
    How to keep track of the separate thread (whether it is completed or not) in java?Thread#join().
    As you're already asking this trival question, I highly recommend you to read the Concurrency Tutorial here at Sun.com. Google can find it.
    Is it possible to read from the file when the thread is writing to the file in java?Not with java.io. You can use the java.nio API for that. You can also read/write it in memory (as a byte[] or a ByteArrayInputStream/OutputStream property) and if it is finished then write it to disk.

  • Frame issue in jsp/struts application

    I have a problem with jsp struts application .
    i have a jsp page which is inside a frame .
    The action class which receives the request from this page redirects the request to another jsp page.
    I want this new jsp page to be displayed without any frame , but it is getting displayed from inside the frame .
    can anybody help me out ...
    regards,               
    slam

    Possibly:
    1. Browser could be caching the page.
    2. If you use a proxy, the proxy may be caching the page.
    3. The page is not getting recompiled.

  • Non-ascii, jsp-struts, not reciveing the correct value in the server

    Hi,
    I am developing JSP-Struts based application using tomcat server. In JSP struts form, when I put nonascii charater in the text field or text area, on the server side I recived twice of that non-ascii character..
    for example, in the text field I entered following string:
    ------> This is text in tex field �ƒ
    On the server side, I get the following:
    ------> This is text in tex field �ƒ�ƒ
    Please notice, twice non ascii character.. :(
    I don't know how to resolve this.. Any help will be greatly appricated..
    Thanks,
    Ajay

    I changed the <form> in the jsp to div and its working fine. I do not need to have comments in JavaScript funcion() anymore. I don't know why that made the difference though? According to:
    http://www.w3schools.com/tags/tag_form.asp
    The <form> tag is used to create an HTML form for user input.
    The <form> element can contain one or more of the following form elements:
    <input>
    <textarea>
    <button>
    <select>
    <option>
    <optgroup>
    <fieldset>
    <label>
    An HTML form is used to pass data to a server.
    I do have <button> and also send the data - the value of checkboxes - to server. So I think it should also work with <form>.
    Please let me know if you have any idea. Thanks.

  • Deploy BC4J/JSP-Struts to IAS

    HI,
    I'm trying to deploy a BC4J/JSP-Struts application to IAS. This application was developed with JDeveloper 9.0.3.
    I can deploy this application to a Standalone OC4J (delivered with JDeveloper 9.0.3) on Windows2000 without problem.
    Then I want to deploy this application on Oracle9iAS 9.0.2. For this I create an .EAR file with JDeveloper and I start the OC4J Administrator tools from Oracle9iAS and deploy my application.
    I start the application with
    http://erbium.int.imd.ch:7778/InvoicesInterface/main.jsp?user=x-XxX
    and I become the menu without Problem.
    Then I click on the link
    http://erbium.int.imd.ch:7778/InvoicesInterface/VInvoiceUsersView1_Browse.do?user=x-XxX
    and I become following :
    HTTP 500 Internal server error
    The page cannot be displayed
    Did you have any Ideas ?
    Thanks Yves
    Configuration:
    - Oracle9iAS (9.0.2) on Solaris
    - JDeveloper9.0.3

    Yves -
    I am not able to pinpoint the exact error you are having but here are some obervations
    a) You are going backwards in versions of OC4J when you deploy to 9iAS 902. If you are using JDev 903, then it is running with a local version of OC4J 903. When you are deploying to 9iAS 902, it's a earlier release of OC4J, so there may be an issue there. There is a 9iAS 903 version available from OTN that would be better to use in this case.
    b) Is the struts framework packaged as part of the EAR file you are deploying? i'm not familiar with how BC4J and Struts apps are packaged from JDeveloper, but this is something to check on for sure. The local OC4J running inside of JDeveloper may have the Struts libs configured at the server level.
    c) You might want to try and change the show-friendly-error-messages (or something like that) property inside of IE (if you are using it) so that it will display the stack trace the server might be sending. this may be of help to further locate the source of the problem (ClassNotFoundException, etc.).
    -steve-

  • Learning JSP/Struts with JDeveloper

    Hi. We have an older version of Java on our Unix production web server (1.4.2_12-b03) and it'll be a year before we upgrade it and use JSF. In the meantime, I'm looking at learning Struts and JSP. Can you point me to a few tutorials specific to JDeveloper for JSP/Struts? Most of the tutorials now are for ADF/JSF -- which we can't use yet. Thanks.

    Just to clarify - JSF can run on OAS 10.1.2 (that supports J2EE 1.3 and uses JDK 1.4).
    See: http://download.oracle.com/docs/html/B25947_01/deployment_topics006.htm#CIHCGGDF
    So this shouldn't be a reason for you not to use JSF and JDeveloper 10.1.3.
    That said if you want to learn Struts try following the archive links on the various JDeveloper tutorials/demos pages to the demos from the 9.0.5/10.1.2 days.

  • SocketInputStream.read(byte[], int, int) extremely slow

    Hi everyone,
    I'm trying to send several commands to a server and for each command read one or more lines as response. To do that I'm using a good old Socket connection. I'm reading the response lines with BufferedReader.readLine, but it's very slow. VisualVM says, that SocketInputStream.read(byte[], int, int) is consuming most of the cpu time. A perl script, which does the same job, finishes in no time. So it's not a problem with the server.
    I'm runnning java version "1.6.0_12"
    Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
    Java HotSpot(TM) Server VM (build 11.2-b01, mixed mode) on Linux henni 2.6.25-gentoo-r7 #3 SMP PREEMPT Sat Jul 26 19:35:54 CEST 2008 i686 Intel(R) Core(TM)2 Duo CPU E6550 @ 2.33GHz GenuineIntel GNU/Linux and here's my code
    private List<Response> readResponse() throws IOException {
            List<Response> responses = new ArrayList<Response>();
            String line = "";
            while ( (line = in.readLine()) != null) {
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                // TODO create different response objects ?!?
                NotImplemented res = new NotImplemented(code, line);
                responses.add(res);
                // we received an "end of response" line and can stop reading from the socket
                if(code >= 200 && code < 300) {
                    break;
            return responses;
        }Any hints are appreciated.
    Best regards,
    Henrik

    Though it's almost an sscce I posted there, I will try to shrink it a little bit:
    Dummy server:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Server {
        public Server() throws IOException {
            ServerSocket ss = new ServerSocket(2011);
            Socket sock = ss.accept();
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintStream ps = new PrintStream(sock.getOutputStream());
            ps.println("200 Welcome on the dummy server");
            String line = "";
            while(line != null) {
                line = br.readLine();
                ps.println("200 Ready.");
        public static void main(String[] args) throws IOException {
            new Server();
    }the client:
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    import de.berlios.vch.Config;
    public class Client {
        private Socket socket;
        private PrintStream out;
        private Scanner scanner;
        public Client(String host, int port, int timeout, String encoding)
            throws UnknownHostException, IOException {
            socket = new Socket();
            InetSocketAddress sa = new InetSocketAddress(host, port);
            socket.connect(sa, timeout);
            out = new PrintStream(socket.getOutputStream(), true, encoding);
            scanner = new Scanner(socket.getInputStream(), encoding);
        public synchronized void send(String cmd) throws IOException {
            // send command to server
            out.println(cmd);
            // read response lines
            readResponse();
        public void readResponse() throws IOException {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                if (code >= 200 && code < 300) {
                    break;
        public static void main(String[] args) {
            try {
                Client con = new Client("localhost", 2011, 500, "utf-8");
                con.readResponse();
                con.send("version 0.1");
                con.send("menu = new menu Feeds");
                con.send("menu.EnableEvent close");
                con.send("menu.SetColorKeyText -red 'Öffnen'");
                for (int i = 0; i < 100; i++) {
                    String groupId = "group"+i;
                    long start = System.currentTimeMillis();
                    con.send(groupId+" = menu.AddNew OsdItem '"+groupId+"'");
                    con.send(groupId+".EnableEvent keyOk keyRed");
                    long stop = System.currentTimeMillis();
                    System.out.println((stop-start)+"ms");
            } catch (Exception e) {
                e.printStackTrace();
    }This code makes me believe, it's not a java problem, but some system setting of my os.

  • How to do it?  Alternate readLine(), read bytes?

    Problem: How to alternate between an InputStreamReader and a raw InputStream when reading data from an InputStream. The catch is that the InputStreamReader may read ahead a few bytes and so subsequent reading from the underlying InputStream will miss those buffered bytes.
    Background:
    I have an application that communicates with a Tomcat servlet with Http protocol.
    I want to send a request, and receive a response as a Java Object. The problem is receiving the response as a Java Object.
    Actually, I have no problem if I use a URLConnection and create an ObjectInputStream from the URLConnection InputStream. But the URLConnection is very slow to use for uploading large files.
    There is a code project called JUpload which uploads files very fast, at least 10 times as fast as URLConnection. It uses sockets and their input/output streams. So I'm adapting some of that code for my application.
    The problem is that the JUpload code is harder to use. It parses the HTTP headers in both directions. When receiving the response, it parses the HTTP headers using an InputStreamReader wrapped in a BufferedReader to read lines, and continues reading lines for any other responses destined to the application.
    However, I need to read a Java object after the header. Therefore, I need to get the underlying InputStream so I can create my ObjectInputStream.
    There is a conflict here. The BufferedReader may (and does) read ahead, so I can't get a "clean" InputStream.
    I have a workaround, but I'm hoping there is a better way. It is this: After reading the HTTP header lines, I read all the remaining characters from the BufferedReader and write them to a ByteArrayOutputStream wrapped in an OutputStreamWriter. Then I create a new ByteArrayInputStream by getting the bytes from the ByteArrayOutputStream. I then "wrap" my ObjectInputStream around the ByteArrayInputStream, and I can read my Java Object as a response.
    This technique is not only clumsy, but it requires buffering everything in memory after the header lines are processed (which happens to be OK for now as my response Object is not large). It also gets really clumsy if the returned HTTP reponse is chunked, because the BufferedReader is needed alternately to read the chunk headers. Fortunately, I haven't encountered a chunked response.
    It feels like what I need is a special Reader object that allows you to alternately read characters or read bytes without "stuttering" (missing buffered bytes).
    I would think the authors of the URLConnection would have encountered this same problem.
    Any thoughts on this would be appreciated.
    -SB
    Edited by: SB4 on Mar 21, 2010 8:08 PM
    Edited by: SB4 on Mar 21, 2010 8:09 PM
    Edited by: SB4 on Mar 21, 2010 8:10 PM

    Yes, that is the problem as you noted. My solution is to continue reading all the characters from the BufferedReader and to convert them back to a byte stream using the ByteArrayOutputStream, OutputStreamWriter, etc.
    It works, just seems clumsy and not scalable.
    I was hoping there might exist a special "CharByteReader" (invented name) class somewhere that would be like a BufferedReader, but that would implement a read(byte[], offset, length) type of method that could access the read-ahead buffer in the same way the read(char[], offset, length) method does.
    URLConnection is just too slow, including chunked mode.

  • GetResourceAsStream problems Read(byte[])

    Heres my code. Some images show up fine, others dont show up at all, and others show up as black images when the images are in a jar file. All images show up fine when they are on the lcoal file system. All images DO fit in the ~60kb byte array. Any suggestions on what the problem is, I have worked around my problem but I would like to know what was going on. My work around was to loop inputstream.read() into the byte array and that has worked.
        public static ImageIcon GetImage(String fileName)
            InputStream iStream=null;
            ImageIcon ic = null;
            try
                if( classLoader == null )
                    try
                        classLoader = Class.forName( "myappclass" ).getClassLoader();
                    catch( Exception x)
                        System.out.println( x.toString() );
                        return ic;
                iStream = classLoader.getResourceAsStream( fileName );
                byte[] bytes = new byte[65000];
                iStream.read(bytes);
               //heres around where it goes caplooyey
                ic = new ImageIcon(bytes);
            catch (IOException ex)
    //            iStream.close();
                System.out.println("No existing file to copy");
                return ic;
            return ic;
        }

    Your code is reading the stream before all the data are available so one read will grab only a partial image. One solution would be to use a BufferedInputStream, but that would consume even more memory than your current approach.
    A much simpler, more efficient, and wholly equivalent technique is accomplished with this one line of code:
    ic = new ImageIcon(ClassLoader.getSystemResource(fileName));

  • After i reading bytes ,how do i get the image to display?

    After i reading bytes ,how do i get the image to display?
    i m lost after tis step:
    Image img=Toolkit.getDefaultToolkit().createImage(data1);

    You can create and use a Canvas. (and define the Paint method)
    Canvas c = new Canvas(){
            public void paint(Graphics g){
                g.drawImage(img,0,0,this);
    frame.add(c);

  • Need info about DataInputStream - read (byte[] ) method

    Hi all,
    I would like to know when does
    datainputStream.read(byte[] buffer) method return?
    Here dataInputStream is an object of type DataInputStream.
    Does the method return only after buffer.length bytes are read from the input stream? or Will it return after some bytes are read , even if the number of bytes read is less than buffer.length?
    I need this info because while developing a J2ME application and running it in an emulator , the above method seems to return even if some bytes are read.But when the application is transferred to a Mobile device, the method does not seem to return if some bytes are read, and seems to wait until buffer.length is reached.

    one more?

  • Read byte from a long

    Hi,
    How can I read bytes from a long. i..e read one byte by one byte from long.
    Naman Patel

    ok here is my problem how do i ignore the sign byte i.e please check this code
    long nr=1345345333L, add=7, nr2=0x12345671L;
              long tmp;
              long[] result = new long[2];
              char[] pwd = password.toCharArray();
              for (int pCount = 0; pCount < pwd.length; pCount++){
                   if (pwd[pCount] == ' ' || pwd[pCount] == '\t')
                        continue;
                   tmp= (long) pwd[pCount];
                   nr^= (((nr & 63)+add)*tmp)+ (nr << 8);
                   nr2+=(nr2 << 8) ^ nr;
                   add+=tmp;
              result[0]=nr & (((long) 1L << 31) -1L); /* Don't use sign bit (str2int) */;
              result[1]=nr2 & (((long) 1L << 31) -1L);
              int i = 0;
              long x = result[0];
              byte b[] = longToBytes(x);
              String str = "";
              i = 0;
              while(i < 4){
                   if(b[i] == 0x00) {
                        System.out.println("byte is 0x00");
                        str += "00";
                   else {
                        if(b[i] <= 0x0f && b[i] >= 0) {
                             System.out.println("byte is 0x0f" + b);
                             str += "0";
                        break;
                   i++;
              i = 0;
              str += Long.toHexString(result[0]);
              x = result[1];
              b = longToBytes(x);
              while(i < 4){
                   if(b[i] == 0x00) {
                        System.out.println("byte is 0x00");
                        str += "00";
                   else {
                        if(b[i] <= 0x0f && b[i] >= 0) {
                             System.out.println("byte is 0x0f");
                             str += "0";
                        break;
                   i++;
              str += Long.toHexString(result[1]);

  • Read byte by byte

    Hi. I'm using the module "bytes at serial port" to read the answers of my robot, but i do not want to read all bytes at the same time. I want to read byte by byte. How can i do it?
    Thanks.
    Ivan.

    So it seems as if ">" is the character that signals the termination of a command.  Use this as your termination character, and initialize the serial port that way.  See picture of how to do this (">" is ASCII 62 in decimal).  When reading, the ">" character will signal the termination and the reading will stop.  Other characters afterwards will remain in the buffer until the next read.
    You should fix your code to prevent infinite loops in case the termination character is not received.  What happens if the character is never sent due to some glitch in the sending system, or if some glitch causes a different character to be received instead of ">", or if the comm link breaks before ">" is received?  Your program will get stuck.  You need to fix this by putting a timeout or something that will abort or end the code in case something goes wrong.
    Message Edited by tbob on 06-12-2006 10:25 AM
    - tbob
    Inventor of the WORM Global
    Attachments:
    Term.png ‏1 KB

  • Issue with reading byte array

    I have a binary file to be read.I want to read the whole file into a byte array. But while doing so the values which are greater than 128 are read as negative values as we have Signedbyte in java(-127 to 128).
    So I tried reading the bytes into the int array as shown in the below code.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
         content= in.readUnsignedByte();
         i++;
    The above function 'readUnsignedByte();' reads byte and stores it into an int array.....But since the file contains around 34000 bytes ....the loop runs 340000 times .....which is a performance hazard.
    After googling for hours ....I could still not find any alternative ....
    I want to read byte and want to store in int array but instead of loop, I want to read the file at once.
    Or is there any way to implement Unsigned Byte in java so that I can read the entire file in byte array without corrupting the values which are greater than 128..
    I have to deliver the code asap .....Please help me out with an alternative solution for this...
    Thanks in advance....

    Thanks for replying ......
    Actually, I need to take the bytes into an array(int or byte array) with decimal values and further process these decimal values.......
    but while reading the file into a byte array the decimal values get corrupted(in case when I read a number greater than 128) but in this case I am able to read the whole file at once(without using any loop) as done by the following code
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         byte b[] = null;
         in.readFully(b);
    and while reading the file in int array as done in the below code is inefficient as the number of times the loop runs is more than 34000..... please suggest me some alternative.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);     
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
                   content= in.readUnsignedByte();
                   i++;

  • Unable 2 read bytes array of images

    I have made a client application which will
    receive an image from server
    the mobile app (clent) is reveiving bytes array in emulator
    but unable 2 receive it in real application...
    message = new byte[2073]; //string 2 read pic;
    for(i=0;i<2073;i++)
    //read pic array byte by byte
    x=is.read(); //(is is an input stream)
    message= (byte)x;
    // also tried this
    //is.read(message)
    works fine in emulator but not in real appication in sony erricson k310i

    sorry actually code was.....
    for reading byte by byte...............
    message = new byte[2073]; //string 2 read pic;
    for(a=0;a<2073;a++)
    //read pic array byte by byte
    x=is.read(); //(is is an input stream)
    message[a]= (byte)x; //problem in last post i[] //converting it into italic
    //for reading whole array message
    // also tried this
    is.read(message)
    and i think there shall be no problem in converting an[b] int into byte

Maybe you are looking for

  • Multiple CardDav accounts, can't delete

    Hi everyone, On my MacBook Pro, iPad and Samsung phone actually I keep all the calendar and contacts sync through a same account of Gmail. With new OS X releases I usually format all my hardrive and later restore part of all the content with Time Mac

  • Search help - Make a field default without grey-out

    Hi, I have a custom-search help, where in the dialog-popup I'd like to default a value without grey-out. If I import from memory via parameter ID, then the default value is ok, but it's greyed out. If I don't import it, then it's initial, but not gre

  • Two company codes under one controlling Area

    In this client, we have two company codes under one controlling Area Will there be any authorisation issues (ie getting the information of other company code date) in Co reports (z reports, standard reports, report painter)? Any thoughts on this is h

  • White balance in photoshop cc

    I only get auto, custom and as shot in choices of white balance in photoshop cc.  I don't know why.

  • Is there a way to find files by their location or drive?

    Hi there. I have moved most of my photos over to an external hard drive, but it looks like a few got missed and I don't really feel like searching through 10K photos to see which ones don't have the offline icon. Is there a way to search for which on