Adding byte arrays of hex numbers

Hi all,
Im having a lot of trouble adding an array of bytes containg a hexidecimal number to another in java. Here is an example of what I want to do (adding 2 byte arrays of hex):
00 00 00 FF
00 00 00 FF
00 00 01 FE
Here is what I have so far:
byte[] ary1 = new byte[]{(byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF}; byte[] ary2 = new byte[]{(byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF};
for (int i = 0; i < ary1.length; i++) {
    ary1[i] += ary2;
This comes out with 00 00 00 FE (using util methods to make the byte array readable as hex). Which is almost right, obviously im missing the overflow. I have no idea how I could detect this in Java, extensive googling has turned up nothing.
Or maybe there is another simpler way to go about this?
please help!

Add the values into an int variable, put the result (cast to byte) into the target array and use (result >> 8) as overflow to add to the next iteration. (Possibly check that overflow at the end of the loop).

Similar Messages

  • Converting a byte array or hex string  into DES key

    i required to covert a hex represented of DES key into key object for cryptography operation to performed ...
    can you help me to find out how to convert a hex representaion of key int DES key object

    hi friend,
    I think the key size is more than the required size. For DES algorithm, the key size is 64 bit long.But the code u have given has more than 64 bit, because of which this exception has been raised.
    Reduce the key value to 64bit and try. If it doesnt work,try the code given below .I think it might be helpful for u
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Cryption
         public byte[] encrypt(byte[] keyData,byte[] clearMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.ENCRYPT_MODE,sks);
                   byte[] encryptedMessage = c.doFinal(clearMessage);
                   return encryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public byte[] decrypt(byte[] keyData,byte[] cipherMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.DECRYPT_MODE,sks);
                   byte[] decryptedMessage = c.doFinal(cipherMessage);
                   return decryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public static void main(String[] args)
              String keyString = "ABCDEF12";
              byte keyValue[] = keyString.getBytes();
              Cryption encryption = new Cryption();
              String Message = "Hello Welcome to world of Cryptography";
              System.out.println("Key Value (represented in HEX form): "+keyString);
              System.out.println("Key Value (represented in byte array form): "+keyValue);
              System.out.println("Original Message : "+Message);
              byte[] encryptedMessage = encryption.encrypt(keyValue,Message.getBytes());
              System.out.println("Encrypted Message : "+new String(encryptedMessage));
              Cryption decryption = new Cryption();
              byte[] decryptedMessage = decryption.decrypt(keyValue,encryptedMessage);
              System.out.println("Decrypted Message : "+new String(decryptedMessage));
    output :
    Key Value (represented in HEX form): ABCDEF12
    Key Value (represented in byte array form): [B@43c749
    Original Message : Hello Welcome to world of Cryptography
    Encrypted Message : "O3�?�M�,����������,�]�3�����R�?>C$
    Decrypted Message : Hello Welcome to world of Cryptography
    whenever u use any algorithm, first findout the key size or range that algorithm supports. It is very important
    regards,
    Deepa Raghuraman

  • Image Byte Array - Hex?

    Hi all,
    I'm trying to read in an image and get an int / hex array out of it. Basically, I want to get an array that would look like what you see if you open an image in a hex editor. I have no problems getting a byte array using..
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ImageIO.write( bufferedImage, "jpg", stream );
    bytes = stream.toByteArray();
    But, it's weird, it's not really what I want. The result is not the same as what I see if I drop the same image into a hex editor and look at the bytes. Not sure if I need to convert the bytes to hex or what. Any help would be much appreciated.

    hmm.. can you explain a bit?.. let's say I do...
    BufferedImage srcImage = ImageIO.read( new File( pathIn ));
    ByteArrayOutputStream streamIn = new ByteArrayOutputStream();
    ImageIO.write( srcImage , "jpg", streamIn );
    byte[] bytes = stream.toByteArray();
    ByteArrayInputStream streamOut = new ByteArrayInputStream( bytes );
    BufferedImage writeImage = ImageIO.read( streamOut );
    ImageIO.write( writeImage, "jpg", new File( pathOut ));Looks a little odd out of context, I know. But, basically, the resulting image is different than the original image. I assume, maybe, there is some sort of compression going on. But i don't really know. Should I be decoding / encoding in specific formats to get the resulting image to be /exactly/ the same as the source?
    thanks

  • Hex code string -- byte array

    hi everyone,
    i have a bunch of hexadecimal code which is read from a text file into a String.
    i want to put this String into a byte array without changing anything.
    my algorithm is like this -
    String strFromTextFile = "FFD8FFE0001";
    * put strFromTextFile into byteArr[ ]
    byteArr[0] == 'F';
    byteArr[1] == 'F';
    byteArr[2] == 'D';

    hi, i think this simple code will fulfill ur need
    public class hex {
         public static void main(String[] args) {
              String str= "AFFD8FFE0001";
              byte hexbytes[] =     hexstore(str);
    public     static byte[] hexstore(String str)
          int length = str.length();
          if((length%2)!=0)
               length++;
               str = new String(str+"0");
          byte[] a = new byte[length/2];
          for(int i=0,j=0;i<str.length();i=i+2,j++)
              byte c =(byte) str.charAt(i);     
              if(c<65)
                   c= (byte)((int)c-48);               
              else
                   c= (byte)(10+(int)c-65);
                   c=(byte)((int)c<<4);
              byte d =(byte) str.charAt(i+1);
              if(d<65)
                   d= (byte)((int)d-48);               
              else
                   d= (byte)(10+(int)d-65);
                   c = (byte)(c | d);
                   a[j]=c;
              for(int i=0;i<length/2;i++)
                   System.out.println("byte "+((int)a));
              return a;
    example ( for first 2 characters)
    AF has to be stored as 1010 1111
    1010 1111 is stoted in a[0];

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • How to create a jar having the contents of the jar in a byte array?

    Hi,
    I have a server and client application. My server returns the contents of the jar in the form of byte array to the client on a particluar method call. Now at the client end, i want to reconstruct the jar to be used. How do I do this?
    The server uses the JarInputStream to read the contents of the jar to be returned. I have tried using the JarOutputStream, but looks like this works fine if we have spearate class files to be added to the jar. Now that I have the contents of the jar itself, how do i recreate the jar?
    Can anyone please help me with this?
    Thanks
    Rajani

    Have you ever gotten the raw byte copy to work? If so, how?
    I download a jar via InputStream and save into a jar file via fileoutputstream. It always gets corrupted in the process. The new Jar file has the exact same number of bytes, but doesn't get past the Manifest on a -tvf. In fact, Winzip can open it fine, but can't extract. So close...yet so far.
    Here is a snapshot of my code:
    BufferedInputStream data1=new BufferedInputStream(con.getInputStream());
    DataInputStream data=new DataInputStream(data1);
    StringBuffer buf=new StringBuffer();
    try{
    while((theChar=data.read()) != -1)
    { buf.append((char)theChar); }
    } catch (Exception z){ logger.info("UpdateThread.read Done Reading jar file");}
    data.close();
    File newFile = new File("C:/MyJar.jar");
    FileOutputStream outstream2 = new FileOutputStream(newFile);
    DataOutputStream outstream1 = new DataOutputStream(outstream2);
    BufferedOutputStream outstream = new BufferedOutputStream(outstream1);
    byte [] bytes = buf.toString().getBytes();
    logger.info("Bytes of new Jar file = " + bytes.length);
    int i;
    for(i=0;i<bytes.length;i++){
    outstream.write(bytes);
    outstream1.close();
    outstream.close();
    Any ideas where I'm going wrong?

  • How to add 16 bit message sequential number to the byte array

    hi
    iam trying to implement socket programming over UDP. Iam writing for the server side now.I need to send an image file from server to a client via a gateway so basically ive to do hand-shaking with the gateway first and then ive to send image data in a sequence of small messages with a payload of 1 KB.The data message should also include a header of 16 bit sequential number and a bit to indicate end of file.
    Iam able to complete registration process(Iam not sure yet).I dnt know how to include sequential number and a bit to indicate end of file.
    I would like to have your valuable ideas about how to proceed further
    package udp;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Sender  {
        protected BufferedReader in = null;
        protected FileInputStream image=null;
        protected static boolean end_of_file=true;
    /** pass arguments hostname,port,filename
    * @param args
    * @throws IOException
       public static void main(String[] args) throws IOException{
            DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[1]));
            boolean more_messages = true;
              String str1=null;
                * gateway registration
                try{
                     //send string to emulator
                    String str="%%%GatewayRegistration SENDER test delay 10 drop 0 dupl 0 bandwidth 1000000";
                    byte[] buff=str.getBytes();
                    InetAddress emulator_address = InetAddress.getByName(args[0]);
                    DatagramPacket packet = new DatagramPacket(buff, buff.length,emulator_address,Integer.parseInt(args[0]));
                    socket.send(packet);
                        // figure out response
                    byte[] buf = new byte[1024];
                    DatagramPacket recpack=new DatagramPacket(buf,buf.length);
                    socket.receive(recpack);
                   // socket.setSoTimeout(10000);
                    String str2=str1.valueOf(new String(recpack.getData()));
                    if(socket.equals(null))
                         System.out.println("no acknowledgement from the emulator");
                        socket.close();
                    else if(str2=="%%%GatewayConfirmation")
                    //     String str1=null;
                         System.out.println("rec message"+str2);
                    else
                         System.out.println("not a valid message from emulator");
                         socket.close();
                catch (IOException e) {
                    e.printStackTrace();
                      end_of_file = false;
         /**create a packet with a payload of 1     KB and header of 16 bit sequential number and a bit to indicate end of file
      while(end_of_file!=false)
          String ack="y";
          String seqnum=
           File file = new File(args[2]);                               
                    InputStream is = new FileInputStream(file);                 
            socket.close();
      private byte[] byteArray(InputStream in) throws IOException {
             byte[] readBytes = new byte[1024]; // make a byte array with a length equal to the number of bytes in the stream
          try{
             in.read(readBytes);  // dump all the bytes in the stream into the array
            catch(IOException e)
                 e.printStackTrace();
            return readBytes;
      

    HI Rolf.k.
    Thank you for the small program it was helpfull.
    You got right about that proberly there  will be conflict with some spurios data, I can already detect that when writing the data to a spreadsheet file.
    I writes the data in such a way, that in each line there will be a date, a timestamp, a tab and a timestamp at the end. That means two columns.
    When i set given samplerate up, that controls the rate of the data outflow from the device, (1,56 Hz - 200 Hz),   the data file that i write to , looks unorderet.
     i get more than one timestamp and severel datavalues in every line and so on down the spreadsheet file.
    Now the question is: Could it be that the function that writes the data to the file,  can't handle the speed of the dataflow in such a way that the time stamp cant follow with the data flowspeed. so i'm trying to set the timestamp to be  with fractions of the seconds by adding the unit (<digit>) in the timestamp icon but its not working. Meaby when i take the fractions off a second within the timestamp i can get every timestamp with its right data value. Am i in deeb water or what do You mean!??
    AAttached Pics part of program and a logfile over data written to file
    regards
    Zamzam
    HFZ
    Attachments:
    DataFlowWR.JPG ‏159 KB
    Datalogfile.JPG ‏386 KB

  • How to make use of byte array to perform credit and debit in Wallet Applet

    Hi,
    Can anyone please explain me how to use the concept of byte arrays.. to perform credit and debit operations of a 6byte amount. Say for example.. the amount contains 3 bytes whole number, 1 byte decimal dot and 2 bytes fractional part.
    It would be helpful if anyone could post a code snippet.. that way i can undersatnd easily.
    Thanks in Advance
    Nara

    Hello
    as explained in the other topic, remember your high school years and how you leart to add numbers.
    then, reproduce these algorithms for base-256 numbers.
    fractional? just google about fixed point math and floating point math. The first one is easier, as they are managed as integers.
    example, you want to store 1,42€. Then you decide the real number to deal with is N*100, and you store 142. You get 2 decimal places of precision.
    in the computer world it's easier to store n*256 as it's just a byte shift.
    then the addition operations are the same, and you just interpret the values as fractional numbers.
    regards
    sebastien

  • Converting an integer to a byte array?

    I have a checksum calculation and i stor it into an int. but when i saved to my test.dat file this number showd up as 05 in hex, which is only 1 byte out of 4 that is displayed. I have been looking around and playin and stuff but havent found anything helpful.
    checksum(4 bytes) : 2126934821
    // Stream access
    FileInputStream fischar;
    FileOutputStream outchar;
    // CS byte array
    byte [] orgCS = new byte[4];
    //byte [] bnewCS = new byte[4];
    int newCS;
    public void writecss() {
    System.out.print( "New checksum(" + 4 + " bytes) : "+newCS+"\n" );
    try{
    // writing original checksum and new checksum into a .dat file spaced with a zero
    outchar = new FileOutputStream( fcs );
    outchar.write(orgCS); // byte array being written
    outchar.write(0);
    outchar.write(0);
    outchar.write(newCS); // Int being written
    outchar.close();
    System.exit(0);
    }catch(IOException ioe){
    // Print IO error
    System.out.print( ioe );
    System.exit(0);
    the output is so
    FD6E 945E 0000 F3 : .n.^...
    you can see where the 2 zero bytes act like a spacer, and you see the integer being cut off for some reason. o_O can you help me out?

    Not sure if this help you?
         * Writes the specified byte to this output stream. The general
         * contract for <code>write</code> is that one byte is written
         * to the output stream. The byte to be written is the eight
         * low-order bits of the argument <code>b</code>. The 24
         * high-order bits of <code>b</code> are ignored.
         * <p>
         * Subclasses of <code>OutputStream</code> must provide an
         * implementation for this method.
         * @param      b   the <code>byte</code>.
         * @exception  IOException  if an I/O error occurs. In particular,
         *             an <code>IOException</code> may be thrown if the
         *             output stream has been closed.
        public void write(int b) throws IOException
         * Writes <code>b.length</code> bytes from the specified byte array
         * to this output stream. The general contract for <code>write(b)</code>
         * is that it should have exactly the same effect as the call
         * <code>write(b, 0, b.length)</code>.
         * @param      b   the data.
         * @exception  IOException  if an I/O error occurs.
         * @see        java.io.OutputStream#write(byte[], int, int)
        public void write(byte b[]) throws IOException Extract from OutputStream API

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • Strange issue with POF: byte array with the value 94

    This is a somewhat strange issue we’ve managed to reduce to this test case. We’ve also seen similar issues with chars and shorts as well. It’s only a problem if the byte value inside the byte array is equal to 94! A value of 93, 95, etc, seems to be ok.
    Given the below class, the byte values both in the array and the single byte value are wrong when deserializing. The value inside the byte array isn’t what we put in (get [75] instead of [94]) and the single byte value is null (not 114).
    Pof object code:
    package com.test;
    import java.io.IOException;
    import java.util.Arrays;
    import com.tangosol.io.pof.PofReader;
    import com.tangosol.io.pof.PofWriter;
    import com.tangosol.io.pof.PortableObject;
    public class PofObject1 implements PortableObject {
         private byte[] byteArray;
         private byte byteValue;
         public void setValues() {
              byteArray = new byte[] {94};
              byteValue = 114;
         @Override
         public void readExternal(PofReader reader) throws IOException {
              Object byteArray = reader.readObjectArray(0, null);
              Object byteValue = reader.readObject(1);
              System.out.println(Arrays.toString((Object[])byteArray));
              System.out.println(byteValue);
              if (byteValue == null) throw new IOException("byteValue is null!");
         @Override
         public void writeExternal(PofWriter writer) throws IOException {
              writer.writeObject(0, byteArray);
              writer.writeObject(1, byteValue);
    Using writer.writeObjectArray(0, byteArray); instead of writer.writeObject(0, byteArray); doesn't help. In this case byteArray would be of type Object[] (as accessed through reflection).
    This is simply put in to a distributed cache and then fetched back. No EPs, listeners or stuff like that involved:
         public static void main(String... args) throws Exception {
              NamedCache cache = CacheFactory.getCache("my-cache");
              PofObject1 o = new PofObject1();
              o.setValues();
              cache.put("key1", o);
              cache.get("key1");
    Only tried it with Coherecne 3.7.1.3.
    Cache config file:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
         <caching-scheme-mapping>
              <cache-mapping>
                   <cache-name>my-cache</cache-name>
                   <scheme-name>my-cache</scheme-name>
              </cache-mapping>
         </caching-scheme-mapping>
         <caching-schemes>
              <distributed-scheme>
                   <scheme-name>my-cache</scheme-name>
                   <service-name>my-cache</service-name>
                   <serializer>
                        <class-name>
                             com.tangosol.io.pof.ConfigurablePofContext
                        </class-name>
                        <init-params>
                             <init-param>
                                  <param-type>string</param-type>
                                  <param-value>pof-config.xml</param-value>
                             </init-param>
                        </init-params>
                   </serializer>
                   <lease-granularity>thread</lease-granularity>
                   <thread-count>10</thread-count>
                   <backing-map-scheme>
                        <local-scheme>
                        </local-scheme>
                   </backing-map-scheme>
                   <autostart>true</autostart>
              </distributed-scheme>
         </caching-schemes>
    </cache-config>
    POF config file:
    <?xml version="1.0"?>
    <pof-config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.oracle.com/coherence/coherence-pof-config"
         xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-pof-config coherence-pof-config.xsd">
         <user-type-list>
              <!-- coherence POF user types -->
              <include>coherence-pof-config.xml</include>
              <user-type>
                   <type-id>1460</type-id>
                   <class-name>com.test.PofObject1</class-name>
              </user-type>
         </user-type-list>
    </pof-config>

    Hi,
    POF uses certain byte values as an optimization to represent well known values of certain Object types - e.g. boolean True and False, some very small numbers, null etc... When you do read/write Object instead of using the correct method I suspect POF gets confused over the type and value that the field should be.
    There are a number of cases where POF does not know what the type is - Numbers would be one of these, for example if I stored a long of value 10 on deserialization POF would not know if that was an int, long double etc... so you have to use the correct method to get it back. Collections are another - If you serialize a Set all POF knows is that you have serialized some sort of Collection so unless you are specific when deserializing you will get back a List.
    JK

  • Use byte array of PDF to display PDF in IE browser

    I get byte array of PDF as input argument. I need to use byte array to display PDF in IE browser. I am writing code in doGet method of Servlet to accomplish this. However, PDF never gets displayed. I see Acrobat starting, but original PDF never gets displayed in browser.
    I am using code below in doGet of Servlet:
    resp.setContentType("application/pdf");
    resp.setHeader("Expires", "0");
    resp.setHeader("Cache-Control","must-revalidate, post-check=0,
    pre-check=0");
    resp.setHeader("Pragma", "public");
    resp.setHeader("Pragma", "no-cache"); //HTTP 1.0
    resp.setDateHeader("Expires", 0); //prevents caching at the proxy
    server
    resp.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    resp.setHeader("Cache-Control", "max-age=0");
    resp.setHeader("Content-disposition", "inline; filename=stuff.pdf");
    byte[] inBytes = getBytesOfPDF(...);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    if(inBytes !=null){
    outStream.write(inBytes);
    outStream.flush();
    I added dummy name of PDF (stuff.pdf) for display, as I heard IE requires a file name with .pdf extension for display.
    But I had no luck with the code above.
    Any help with code will be appreciated.
    [email protected]

    Hi
    Am using the same code and i am able to get the PDF out.
              /* Finally writing it into a PDF */
                   response.setContentType("application/pdf");
                   /* filename could be any thing */
                   response.setHeader("Content-Disposition",
                             "attachment; filename=Report.pdf");
                   response.setContentLength(content.length);
                   response.getOutputStream().write(content);
                   response.getOutputStream().flush();
    But this also throws a error in the server :
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         at org.apache.catalina.connector.Response.getWriter(Response.java:606)
         at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:195)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:344)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:280)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:225)
         at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:174)
         at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:239)
         at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1142)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:879)
         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792)
         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476)
         at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:441)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
         at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
         at org.ca.ielts.presentationtier.servlet.AuthorisationAuthenticationFilter.doFilter(Unknown Source)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    Any Clues how this has to be fixed.????

  • Byte array to png image conversion

    hi friends
    i am using a servlet using tomcat server to send multiple images to a client. i have stored all the images in a single byte array.and then encoded using base64. i am sending it to the client side and decoding it. when i extract the byte array and then try to convert it to image it shows an illegal argument exception.please help me?
    Pradeep

    dubwai
    Just looked at your code again. Did you mean int,not
    long?He wanted an unsigned int (which of course doesn't
    exist in Java) and if you look at his original code it
    was returning long.Well, it's not so much that I wanted an unsigned int, it's just that the data was stored as a 32 bit unsigned integer. Since the data represented numbers with a range of 0 to 2^32 - 1, the range exceeded what I could put in a Java int, thus I need to stuff it in a long - well, that was my reasoning anyway.
    Thanks for the nio tip, I'd not looked into that stuff and really should.
    Lee
    Thanks much for the code -

  • MD5 - Size Of Digested Byte Array

    Hey There.
    After MD5 digesting and then Base64Encoding a string, I would end up with a byte array such as this:
    GH70Q2Ei0cwvQNwrkvDroA==
    It changes with the input, but is always 24 characters in length. I would have thought it to be 32 characters. Any reasons???
    I'm doing the UTF-8 thing. Refer to code in previous post where I'm looking for critique of code.
    Thanks,
    Vic

    I do think about what I'm doing. I know I have to
    encode digested value to get data into db. I'm not
    aware of HEX encoding, only BASE64.If you aware of Base64 and MD5, I suppose you know the digest size produced by MD5 and the fact that Base64 increases the size of encoded data to fixed percentage (which is less then 50%).

Maybe you are looking for

  • Is there a way to force the charset to utf-8 with the IIS plug-in?

    We're using AJAX. The initial request for the HTML has charset=utf-8 set on the HTTP header as seen in this Live HTTP Headers capture: http://plper.mysite.com/mysupport/index.jsf GET /mysupport/index.jsf HTTP/1.1 Host: plper.mysite.com User-Agent: Mo

  • Import statement not found for javax.mail.Message

    when i'm in webSphere shich is using jdk1.4.2, import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; cannot be found Where

  • Sun StorEdge 3510

    Dears, Good day, I need your support to guide me to configure Sun StorEdge 3510. I have 24 Disks and single controller. I is connected to one host. I want to configure it with the most biggest storage. I want to implement RAID 5 on 11 disks on the fi

  • Creating SAP users using Program RHPROFL0

    Hi Experts, I want to create SAP users and assign authorisation using program RHPROFL0. Whenever I execute this program Generate new user field is greyed out. I can not select it to create users. I have already activated switch 'ORGPD' for Structural

  • If anyone's got JDeveloper to work.....

    ..could you please post details of your NT/Oracle software levels, as seemingly everything I try on JDeveloper results in it hanging, particulary when trying to run an applet that connects to a database. I'm running NT SP4 with Oracle 8.0.5. server i