Pointer to a 32 byte buffer

Dear all,
I need to initialize a dll parameter like this - a pointer to a 32 byte array.
Could somebody please tell how to configure that?
Thanks,
Mathan

Hi Gerdw,
You mean like this????
Thanks,
Mathan
Attachments:
untitled2.PNG ‏64 KB
untitled3.PNG ‏52 KB

Similar Messages

  • Install(byte[] buffer,short offset, byte length)

    Anyone could tell me where i can find the defination of data format of 'buffer' in 'install(byte[] buffer,short offset, byte length)', it is standard, right?!

    Look in appendix A.2 of the GlobalPlatform Card Specifications 2.1.1 (pages 160,161). The same information is specified for the install() method in the Java Card 2.2 API spec. The format is the same for Java Card 2.1.1 and GlobalPlatform 2.0.1'.
    G

  • Floating point number to IBM bytes

    Hello,
    I'm trying to convert a float value to a byte array (but in IBM standard).
    I understand that the general idea will be the following algorithm:
    1. process the sign, exponent and fraction from the float value (using IBM standard)
    2. build the bytes from the S, E, F from step 1.
    So far, I only have the step 2 like this:
    public static byte[] toBytesIbm( int signBit, int exponent, long fraction ) {
    byte[] bytes = new byte[4];
    bytes[0] = (byte)(signBit + exponent);
    bytes[1] = (byte)((fraction & 0x00FF0000) >> 16);
    bytes[2] = (byte)((fraction & 0x0000FF00) >> 8);
    bytes[3] = (byte)(fraction & 0x000000FF);
    return bytes;
    Getting the sing bit is also not a problem, so the real work is in getting the exponent and fraction from the number. I don't know how to do this. I have code from a trusted source to convert from IBM bytes to IEEE float numbers, so I can check if the bytes are correct.
    Can anyone help me with this?
    Thanks in advance

    Brushfire wrote:
    Thanks for the correct. I'm never quite sure about the masks, but I've had issues with extra data being introduced before, so I like it better safe than sorry. The mask is needed when a narrower primitive has been sign-extended to a wider primitive, and you want to keep the result unsigned.
    But in this case, the result is then cast to byte, which removes all the upper bits that the mask was trying to set to zero in the first place.
    If you need to store a byte in an int without sign-extension, you need a mask:
    int n = someByte & 0xFF;If you want to store the lower 8 bits of an int in another int, you need a mask:
    int lowerEight = someInt & 0xFF;But if you want to store the lower 8 bits in a byte, just cast:
    byte lowerEight = (byte)someInt;

  • SOCKET BYTE BUFFER SIZE LIMIT

    Dear users,
    I am using one application working in the Weblogic 6.1 Env. This application is working as the server for a client application working out of weblogic env.
    The problem i am facing is when i send some data from the server socket to client socket the data is all broken after a certain limit of bytes ... is there some hidden limit for sending data through sockets in Weblogic Env??
    How can i control this?
    Do help/
    Thanks

    I am using one application working in the Weblogic 6.1 Env. Thisapplication is working as the server for a client application working out of
    weblogic env.
    The problem i am facing is when i send some data from the server socket toclient socket the data is all broken after a certain limit of bytes ... is
    there some hidden limit for sending data through sockets in Weblogic Env??
    Usually this indicates that the streams are not being flushed correctly.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "Ravi Pal" <[email protected]> wrote in message
    news:3fe146aa$[email protected]..
    >

  • Constructing a buffer to hold bytes going to socket

    I'm a newbie and struggling with a project to construct a multi-threaded Web server that enables a browser-client to access an HTML file. I've constructed a 1K buffer, but if I want to examine various file transfer rates with different file sizes, I have to recode and recompile. How do I construct the buffer so that I can change the transfer rate and the file sizes without having to recode/recompile? The portion of my code relating to buffer construction is as follows:
    private static void sendBytes(FileInputStream fis, OutputStream os)
              throws Exception
              //Construct a 1K buffer to hold bytes on their way to the socket
              byte[] buffer = new byte[1024];
              int bytes = 0;
              //Copy requested file into the socket's output stream
              while((bytes = fis.read(buffer)) != -1)
                   os.write(buffer, 0, bytes);
         private static String contentType(String fileName)
              if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
                   return "text/html";
              if (fileName.endsWith(".jpg"))
                   return "image/jpeg";
              if (fileName.endsWith(".gif"))
                   return "image/gif";
              return "application/octet-stream";
    }

    Use a system property. When you run your program:
    java -Dbuffer.size=4096 ...
    Then in your code:
    int bufsize = Integer.get("buffer.size", 1024).intValue();
    byte[] buffer = new byte[bufsize];

  • Sending a byte array of greater length than the APDU data buffer

    Hello again, I am now trying to send a byte array of length 480 from the smart card. I've tried setting the outgoing length to 480 first but as i had expected, this threw an exception. Then i tried setting it to 240 and then copying from the array into the apdu buffer in two halves and calling sendBytes() twice, but this only worked the first time - it send the first 240 bytes and then threw an error. Is it possible to do what i am trying to accomplish? If so, what am I missing?

    the applet:
    H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src\com\sun\javacard\samples\photocard
    the client:
    H:\java_card_kit-2_2_1-win-dom\java_card_kit-2_2_1\samples\src_client\com\sun\javacard\clientsamples\photocardclient
    here is the code i have used to store large data on card. maybe it will help you.
    i send a series of apdu, where each contains 128 bytes of data (all apdu must have the same length - except the last).
    public void writeAPDU(APDU apdu)
         byte[] buffer = apdu.getBuffer();
         short lc = (short)(buffer[ISO7816.OFFSET_LC]&0xFF);          
         short p1 = (short)(buffer[ISO7816.OFFSET_P1]&0xFF); // counter
         short p2 = (short)(buffer[ISO7816.OFFSET_P2]&0xFF); // length of send data
         short offset = (short)(p1 * p2); // calculate the offset
         apdu.setIncomingAndReceive();
         // check for first apdu (contains the total size of data)
         if(p1 == 0 && p2 == 0)
              short l = Util.getShort(buffer,ISO7816.OFFSET_CDATA);
              data = new byte[l];
         else
              // store bytes in array
              Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, data, offset, lc);
    }

  • Error when creating BufferedImage with IndexColorModel from a byte array.

    Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
    The color model I have is:
    int [] cmap = new int [numColors];
    cmap[i++] = 0xffa0f000;  /etc.
    new IndexColorModel(8, 22, cmap, 0, true,  transparentIndex,  DataBuffer.TYPE_BYTE );Thanks for your help
    -Ben
    Ps.
    I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
    [java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
    [java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    Code:
    byte[] pixelArray = (byte[]) getData_CHAR();                
    int width = 5120;
    int height = 3520;
    int numbytes = width*height;
    //create DataBuffer using byte buffer of pixel data.
    DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
    //prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
    int bitMasks[] = new int[]{0xf};
    SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
    //create a raster using the sample model and data buffer
    WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
    //generate 16-color model
    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    r[0] = 0; g[0] = 0; b[0] = 0;
    r[1] = 0; g[1] = 0; b[1] = (byte)192;
    r[2] = 0; g[2] = 0; b[2] = (byte)255;
    r[3] = 0; g[3] = (byte)192; b[3] = 0;
    r[4] = 0; g[4] = (byte)255; b[4] = 0;
    r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
    r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
    r[7] = (byte)192; g[7] = 0; b[7] = 0;
    r[8] = (byte)255; g[8] = 0; b[8] = 0;
    r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
    r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
    r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
    r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
    r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
    r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
    r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
    //create buffered image    
    ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
    BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
    ben_weisburd
    Message was edited by:
    ben_weisburd

    I had the same problem too.
    anyone found the solution for this problem?
    thanks
    Bruno Rabino
    When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
    Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
    Error creating module: ORA-01403: no data found (WWV-16042)
    When I use the table with the BLOB as master or in a form, it works fine.
    Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
    Portal version: 3.0.6.6.5
    null

  • Sending command apdu with a byte array as CDATA

    Hi,
    I am learning java card as part of my final year project. So far I think I can do most of the basic things but I have got stuck at one particular point.
    I know that there are different constructors for creating a command apdu object and a number of these constructors take an array of bytes as CDATA values.
    My problem is, how to access this array of data in the card side because apdu.getBuffer() returns an array of integers (bytes)? And what is actually on apdu.getBuffer()[ISO7816.OFFSET_CDATA)] location when you send command apdu object using such a constuctor?
    regards
    Edited by: 992194 on 06-Mar-2013 06:12

    992194 wrote:
    (..) I should have mentioned earlier that my card use jc 2.2.1 version, and i have read from different places that this version does not support ExtendedLength facility.Indeed.
    Also I understand the semantics of apdu.getBuffer()[ISO7816.OFFSET_CDATA] that is the first byte of the command data. My question is, this command data was initially supplied as an array of bytes. Something like this:
    +new CommandAPDU(CLA, INS, P1, P2, DATA_ARRAY, Le)+
    So when you call:
    byte [] buffer = apdu.getBuffer()
    So does this mean that the byte values inside DATA_ARRAY automatically occupy locations +buffer[ISO7816.OFFSET_CDATA]+ onwards inside the buffer?Yes. The length would be<tt> (short)(buffer[ISO7816.OFFSET_LC]&0xFF) </tt>. Notice the<tt> &0xFF </tt> is a must above 127 bytes.
    Or their is a mechanism of extracting the DATA_ARRAY array itself?No.
    In fact, in the interest of performance and portability in environments with little memory, the usual coding style is to pass<tt> buffer </tt>, an offset within that, and the length; rather than making an object, which would require a copy. Welcome to the real world of Java Card.

  • Serial VISA 'Write' -why is it slow to return even with large buffer?

    Hi,
    I'm writing a serial data transfer code 'module' that will run 'in the background' on a cRIO-9014.  I'm a bit perplexed about how VISA write in particular seems to work.
    What I'm seeing is that the VISA Write takes about 177ms to 'return' from a 4096 byte write, even though my write buffer has been set to >> 4096.
    My expectation would be that the write completes near instantly as long as the VISA driver available buffer space is greater than the bytes waiting to be written, and that the write function would only 'slow down' up to the defined VISA timeout value if there was no room in the buffer.
    As such, I thought it would be possible to 'pre-load' the transmit buffer at a high rate, then, by careful selection of the time-out value relative to the baud rate, it would self-throttle once the buffer fills up?
    Based on my testing this is not the case, which leaves me wondering:
    a) If you try to set the transmit buffer to an unsupported value, will you get an error?
    b) Assuming 'yes' to a, what the heck is the purpose of the serial write buffer? I see no difference running with serial buffer size == data chunk size and serial buffer size >> data chunk size??
    QFang
    CLD LabVIEW 7.1 to 2013

    Hi, I can quickly show the low-level part as a png. It's a sub-vi for transferring file segments.  Some things like the thin 'in-line' VI with (s) as the icon were added to help me look at were the hold-up is.  I cropped the image to make it more readable, the cut-off left and right side is just the input and output clusters.
    In a nut-shell, the VISA Write takes as much time to 'return' as it would take to transfer x bytes over y baud rate.  In other words, even though there is suppused to be a (software or hardware) write and read buffer on the com port, the VISA write function seems to block until the message has physically left the port (OR it writes TO the buffer at the same speed the buffer writes out of the port).  This is very unexpected to me, and what prompted me to ask about what the point is of the write buffer in the first place?  -The observations are on a 9014 RT target built in serial port.  Not sure if the same is observed on other targets or other OS's.  [edit: and the observation holds even if transmitting block-sizes of say 4096 with a buffer size of 4096 or 2*4096 or 10 * 4096 etc. I also tried smaller block sizes and larger block sizes with larger still buffers.  I was able to verify that the buffer re-size function does error out if I give it an insane input buffer size request, so I'm taking that to mean that when I assign e.g. a 4MiB buffer space with no error, the write buffer actually IS 4MiB, but I have not found a property to read back what the HW buffer is, so all I have to base that on is the lack of an error during buffer size setting.) [\edit\]
    The rest of the code is somewhat irrelelvant to this discussion, however, to better understand it, the idea is that the remote side of the connection will request various things, including a file.  The remote side can request a file as a stream of messages each of size 'Block Size (bytes)', or it can request a particular block (for handling e.g. re-transmission if file MD5 checksum does not match).   The other main reason for doing block transfers is that VISA Write hogs a substantial ammount of CPU, so if you were to attempt to write e.g. a 4MiB file out the serial port, assuming your VISA time-out is sufficiently long for that size transfer, the write would succeed, but you would see ~50% CPU from this one thread alone and (depending on baud rates) it could remain at that level for a verrry long time.   So, by transferring smaller segments at a time, I can arbitrarily insert delays between segments to let the CPU sleep (at the expense of longer transfer times).  The first inner case shown that opens the file only runs for new transfers, the open file ref is kept on a shift register in the calling VI.  The 'get file offset' function after the read was just something I was looking at during (continued) development, and not required for the functionality that I'm describing.
    QFang
    CLD LabVIEW 7.1 to 2013

  • How to clear byte array

    Hi, here are the codes
    byte[] buffer = new byte[1000];
    // use the buffer for something else
    then How can I clear the content of this buffer,
    so I can use it for TCP/IP datainstream again
    int result=in.read(buffer);
    Thank you very much.

    Hi, here are the codes
    byte[] buffer = new byte[1000];
    // use the buffer for something else
    then How can I clear the content of this buffer,
    so I can use it for TCP/IP datainstream again
    int result=in.read(buffer);
    Thank you very much. You shouldn't have to clear the buffer. The read() method returns the number of bytes read, so you know not to read past that point in the buffer.
    As an example, here is some code that reads from one stream and writes to another. Note that I use the 3 parameter version of write() to make sure I only use the part of the buffer that actually got filled by the last call to read(). In the following, os is an OutputStream and is is an InputStream.
                        byte[] buf = new byte[1024];
                        int count = 0;
                        while((count=is.read(buf))!=-1) {
                          os.write(buf, 0, count);
                        }

  • Nfs mount point does not allow file creations via java.io.File

    Folks,
    I have mounted an nfs drive to iFS on a Solaris server:
    mount -F nfs nfs://server:port/ifsfolder /unixfolder
    I can mkdir and touch files no problem. They appear in iFS as I'd expect. However if I write to the nfs mount via a JVM using java.io.File encounter the following problems:
    Only directories are created ? unless I include the user that started the JVM in the oinstall unix group with the oracle user because it's the oracle user that writes to iFS not the user that creating the files!
    I'm trying to create several files in a single directory via java.io.File BUT only the first file is created. I've tried putting waits in the code to see if it a timing issue but this doesn't appear to be. Writing via java.io.File to either a native directory of a native nfs mountpoint works OK. ie. Junit test against native file system works but not against an iFS mount point. Curiously the same unit tests running on PC with a windows driving mapping to iFS work OK !! so why not via a unix NFS mapping ?
    many thanks in advance.
    C

    Hi Diep,
    have done as requested via Oracle TAR #3308936.995. As it happens the problem is resolved. The resolution has been not to create the file via java.io.File.createNewFile(); before adding content via an outputStream. if the File creation is left until the content is added as shown below the problem is resolved.
    Another quick question is link creation via 'ln -fs' and 'ln -f' supported against and nfs mount point to iFS ? (at Operating System level, rather than adding a folder path relationship via the Java API).
    many thanks in advance.
    public void createFile(String p_absolutePath, InputStream p_inputStream) throws Exception
    File file = null;
    file = new File(p_absolutePath);
    // Oracle TAR Number: 3308936.995
    // Uncomment line below to cause failure java.io.IOException: Operation not supported on transport endpoint
    // at java.io.UnixFileSystem.createFileExclusively(Native Method)
    // at java.io.File.createNewFile(File.java:828)
    // at com.unisys.ors.filesystemdata.OracleTARTest.createFile(OracleTARTest.java:43)
    // at com.unisys.ors.filesystemdata.OracleTARTest.main(OracleTARTest.java:79)
    //file.createNewFile();
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buffer = new byte[1024];
    int noOfBytesRead = 0;
    while ((noOfBytesRead = p_inputStream.read(buffer, 0, buffer.length)) != -1)
    fos.write(buffer, 0, noOfBytesRead);
    p_inputStream.close();
    fos.flush();
    fos.close();
    }

  • Storing input stream in a buffer

    Hi, what is the best way to read an input stream and save it into a buffer?
    Thanks,
    Andrea

    Not sure if any of the following are an improvement or not. But here are just a few thoughts. Why handle all the byte array allocation yourself? IMO, it would be easier to simply use a ByteArrayOutputStream at that point. The listeners can call toByteArray() and be passed an offset and length of what was read.
    Now that I think about it, you could probably make it a bit more generic even than that. For example, here is a class I end up using all the time:
    public final class Pipe
        /** Buffer size to read in and output. */
        private static final int DEFAULT_BUFFER_SIZE = 2048;
         * Private constructor.  Use public static facade methods instead.
        private Pipe()
            super();
         * Pipes the specified binary data to the specified output stream.
         * @param   target                      Binary data to output
         * @param   out                         Stream to write
         * @throws  IOException
        public static final void pipe(final byte[] target, final OutputStream out)
            throws IOException
            assert (target != null) : "Missing byte array";
            assert (out != null) : "Missing output stream";
            pipe(new ByteArrayInputStream(target), out, true);
         * Reads from the specified input stream and returns all data as an in-memory.
         * binary array.  Note:  Since streams may be of any arbitrary size, this
         * method requires that you wrap your original stream in a {@link FiniteInputStream}.
         * Please ensure that this method is only used to read in data under, say, 2mB.
         * @param   in                          Stream to read
         * @return  byte[]                      Binary data read
         * @throws  IOException
        public static final byte[] pipe(final FiniteInputStream in)
            throws IOException
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            pipe(in, byteOut, true);
            return byteOut.toByteArray();
         * Reads from the specified input stream and outputs immediately to the specified.
         * output stream.  <br>
         * <br>
         * If you have any confusion about which <code>Pipe</code> method to use, choose
         * this one.  It has the lowest memory overhead and is the most efficient.  Always
         * choose this method when streaming large amounts of data or content.
         * @param   in                          Input stream to read
         * @param   out                         Output stream to write
         * @param   close                       Close both stream if true
         * @return  long                        Byte count piped
         * @throws  IOException
        public static final long pipe(final InputStream in, final OutputStream out, final boolean close)
            throws IOException
            assert (in != null) : "Missing input stream";
            assert (out != null) : "Missing output stream";
            long bytesPiped = 0L;
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            try
                int bytesRead = in.read(buffer);
                while (bytesRead >= 0)
                    if (bytesRead > 0)
                        out.write(buffer, 0, bytesRead);
                        bytesPiped = bytesPiped + bytesRead;
                    bytesRead = in.read(buffer);
                out.flush();
                return bytesPiped;
            finally
                if (close)
                    IoHelper.close(in);
                    IoHelper.close(out);
    }You simply could add the listener feature (which I do think is useful and elegant). Note the FiniteInputStream and FiniteOutputStream are just sub-classes of FilterInputStream and FilterOutputStream that allow you to limit how many bytes are piped, if desired.
    - Saish

  • I want the Bytes opened as Bytes not Characters ?

    Hi,
    Here is my assignment main points:
    1. Get File:
    I use file = fd.getSelectedFile(); to get the file content, and
    String filename = file.getName(); to get the file name
    Two things must be sent to the Server; the file name and the file content.
    2. Sending the file to Server:
    //Get a reference to the socket's output streams
    DataOutputStream os = new DataOutputStream(socket.getOutputStream());
    //Opens the requested file.
    FileInputStream fis = null;
    boolean fileExists = true;
    try {
    fis = new FileInputStream(file);
    } catch (FileNotFoundException e) {
    fileExists = false;
    if (fileExists)
    //Construct a 1K buffer to hold the bytes on their way to the socket
    byte[] buffer= new byte[1024];
    int bytes = 0;
    //Copy requested file into the socket's output stream.
    while((bytes = fis.read(buffer)) != -1)
    os.write(buffer, 0, bytes);
    // Close the file
    fis.close();
    *The file has been sent to the Server as a Byte Buffers through DataOutputStream
    3. Open the file in Server side:
    // Receive the file
    InputStream is = client.getInputStream();
    BufferedReader breader = new BufferedReader( new InputStreamReader(is));
    // Read the file as String
    String line;
    StringBuffer builder = new StringBuffer();
    while ( (line = breader.readLine()) != null){
    builder.append(line);
    builder.append(" ");
    String text = builder.toString();
    *The file has been opened as a text .
    4. Print the File:
    printText( text );
    The file has been printed as a text .
    Problems I faced are:
    1. I dont know how to send the file name + file content, now I can just send the content of the file, I know that some modification must be done in 2. Sending the file to Server, but I don't know how?
    2. I dont want to recieve the file in Server side as text, instead I want to recieve it as a bytes so I can print any type of file, how to do that?
    Any Advice? or sample code ?
    Thanks in advance.

    I don't see the problem. Use DataOutputStream's writeUTF and DataInputStream's
    readUTF for the filename and write and read bytes for the filecontent. Don't
    use Readers or Writers.

  • Sample Javacard 2.2.1 Electronic wallet, Loyalty Points & StudentID applet

    Hi All,
    After nine months of researching and developing a java card applet and terminal side interface for my final year university project I was frustrated with the lack of sample code and tutorials available online.
    My applet is aimed at students as an id card containing a student id, all the features of an electronic wallet, loyalty point system protected by a pin number. Pin is changeable.
    The terminal interaction or host side application that communicates with this applet can be found in this forum under the heading "Sample Smartcardio (Host side) applet interaction application".
    As I have no finished my project I would like to share it with anyone that would like to see it.
    While I would love to write a tutorial I simply do not have the time however below is the applet I used in my project, I how for anyone that has read through java sun's tutorials this will be a help:
    package account;
    import javacard.framework.APDU;
    import javacard.framework.APDUException;
    import javacard.framework.ISO7816;
    import javacard.framework.Applet;
    import javacard.framework.ISOException;
    import javacard.framework.OwnerPIN;
    import javacard.framework.TransactionException;
    import javacard.framework.Util;
    * @Raymond_Garrett
    * DT 354-4
    *Applet ID 41 63 63 6F 75 6E 74 41 70 70 6C 65 74
    public class AccountApplet extends Applet {
         // codes of CLA byte in the command APDUs
         final static byte ACCOUNT_CLA = (byte)0xA0;
         // codes of INS byte in the command APDUs
         final static byte VERIFY_INS = (byte) 0x20;
         final static byte CREDIT_INS = (byte) 0x30;
         final static byte DEBIT_INS = (byte) 0x40;
         final static byte GET_LOYALTYPOINTS_BALANCE_INS = (byte) 0x45;
         final static byte CREDIT_LOYALTYPOINTS_INS = (byte) 0x47;
         final static byte GET_BALANCE_INS = (byte) 0x50;
         final static byte UPDATE_PIN_INS = (byte) 0x60;
         final static byte ADMIN_RESET_INS = (byte) 0x70;
         final static byte PIN_TRIES_REMAINING_INS = (byte) 0x80;
         final static byte STUDENT_NUMBER_INS = (byte) 0x90;
         // maximum Account balance
         final static short MAX_BALANCE = 10000;
         // maximum transaction amount
         final static short MAX_TRANSACTION_AMOUNT = 5000;
         // maximum number of incorrect tries before the
         // PIN is blocked
         //Changed to 4, as a safe guard all. All tests, messages and checks will use 3
         final static byte PIN_TRY_LIMIT =(byte)0x04;
         // maximum size PIN
         final static byte MAX_PIN_SIZE =(byte)0x08;
         // Applet-specific status words:
         final static short SW_NO_ERROR = (short) 0x9000;
         final static short SW_VERIFICATION_FAILED = 0x6300;
         final static short SW_PIN_VERIFICATION_REQUIRED = 0x6301;
         final static short SW_INVALID_TRANSACTION_AMOUNT = 0x6E83;
         final static short SW_EXCEED_MAXIMUM_BALANCE = 0x6E84;
         final static short SW_NEGATIVE_BALANCE = 0x6E85;
         final static short SW_PIN_TO_LONG = 0x6E86;
         final static short SW_PIN_TO_SHORT = 0x6E87;
    //     Student number (Ascii)d05106012 - (Hex)44 30 35 31 30 36 30 31 32
         private static byte[] STUDENT_NUMBER_ARRAY = {(byte)0x44, (byte)0x30, (byte)0x35, (byte)0x31, (byte)0x30, (byte)0x36, (byte)0x30, (byte)0x31, (byte)0x32};
         // instance variables declaration
         OwnerPIN pin;
         short balance = 1000; // Starting balance of decimal 1000 is 3E8 in hex
         short loyaltyPoints = 0; //Loyalty points
         // 1 Loyalty point awarded for every 100 cent spent.
          * install method
         public static void install(byte[] bArray, short bOffset, byte bLength) {
              // GP-compliant JavaCard applet registration
              new AccountApplet(bArray, (short) (bOffset + 1), bArray[bOffset]);
          * Constructor
          * @param bArray
          * @param bOffset
          * @param bLength
         private AccountApplet(byte[] bArray, short bOffset, byte bLength){
              pin = new OwnerPIN(PIN_TRY_LIMIT, MAX_PIN_SIZE);
              // bArray contains the default PIN initialization value (12345)
              bArray[0] = 01;
              bArray[1] = 02;
              bArray[2] = 03;
              bArray[3] = 04;
              bArray[4] = 05;
              bOffset = 0;
              bLength = 5;
              pin.update(bArray, bOffset, bLength);
              // register the applet instance with the JCRE
              register();
         } // end of the constructor
          * Boolean is selected
         public boolean select() {
              // the applet declines to be selected
              // if the pin is blocked
              if (pin.getTriesRemaining() == 0)
                   return false;
              return true;
         } // end of select method
          * deselect
         public void deselect() {
              // reset the pin
              pin.reset();
          * Key method the gets the APDU reads the INS and calls the appropiate method
          * Process APDUs
          * @param apdu
         public void process(APDU apdu) {
              // APDU object carries a byte array (buffer) to
              // transfer incoming and outgoing APDU header
              // and data bytes between the card and the host
              // at this point, only the first five bytes
              // [CLA, INS, P1, P2, P3] are available in
              // the APDU buffer
              byte[] buffer = apdu.getBuffer();
              // return if the APDU is the applet SELECT command
              if (selectingApplet())
                   return;
              // verify the CLA byte
              if (buffer[ISO7816.OFFSET_CLA] != ACCOUNT_CLA)
                   ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
              // check the INS byte to decide which service method to call
              switch (buffer[ISO7816.OFFSET_INS]) {
              case GET_BALANCE_INS:                    getBalance(apdu);                return;
              case DEBIT_INS:                              debit(apdu);                       return;
              case CREDIT_INS:                         credit(apdu);                     return;
              case VERIFY_INS:                         verify(apdu);                    return;
              case UPDATE_PIN_INS:                    updatePin(apdu);               return;
              case ADMIN_RESET_INS:                    adminRest();                    return;
              case PIN_TRIES_REMAINING_INS:           getPinTriesRemaining(apdu); return;
              case STUDENT_NUMBER_INS:                getStudentNumber(apdu);       return;
              case GET_LOYALTYPOINTS_BALANCE_INS:     getLoyaltyPoints(apdu);      return;
              case CREDIT_LOYALTYPOINTS_INS:       creditLoyaltyPoints(apdu);      return;
              default:                    ISOException.throwIt
              (ISO7816.SW_INS_NOT_SUPPORTED);
         } // end of process method
          * verify then
          * withdraw money from the Account balance
          * @param apdu
         private void debit(APDU apdu) {
              // verify authentication
              if (!pin.isValidated()){
                   ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
              byte[] buffer = apdu.getBuffer();
              // get the number of bytes in the
              // data field of the command APDU
              byte numBytes = buffer[ISO7816.OFFSET_LC];
              //receive data
              //data is read into apdu buffer
              //at offset ISO7816.OFFSET_CDATA
              byte byteRead = (byte)(apdu.setIncomingAndReceive());
              short shortAmount = 0;
              if (numBytes == 2){
                   shortAmount = (short) Util.getShort(buffer, ISO7816.OFFSET_CDATA);
              else if (numBytes == 1) {
                   shortAmount = (short) buffer[ISO7816.OFFSET_CDATA];
              // check the debit amount
              if (( shortAmount > MAX_TRANSACTION_AMOUNT)     || ( shortAmount < 0 )) {
                   ISOException.throwIt(SW_INVALID_TRANSACTION_AMOUNT);
              // check the new balance
              if ((short)( balance - shortAmount)  < 0) {
                   ISOException.throwIt(SW_NEGATIVE_BALANCE);
              // debit the amount
              balance = (short)(balance - shortAmount);
              //Add loyalty points
              loyaltyPoints = (short) (loyaltyPoints + (short)(shortAmount/100));
              return;
         }          // end of debit method
         

    Code continued>>>>>>>>
          * Verify then
          * add money (credit) to the Account balance
          * @param apdu
         private void credit(APDU apdu) {
              // verify authentication
              if (!pin.isValidated()){
                   ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
              byte[] buffer = apdu.getBuffer();
              // get the number of bytes in the     
              // data field of the command APDU
              byte numBytes = buffer[ISO7816.OFFSET_LC];
              //receive data
              //data is read into apdu buffer
              //at offset ISO7816.OFFSET_CDATA
              byte byteRead = (byte)(apdu.setIncomingAndReceive());
              short shortAmount = 0;
              if (numBytes == 2){
                   shortAmount = (short) Util.getShort(buffer, ISO7816.OFFSET_CDATA);
              else if (numBytes == 1) {
                   shortAmount = (short) buffer[ISO7816.OFFSET_CDATA];
              // check the credit amount
              if (( shortAmount > MAX_TRANSACTION_AMOUNT)     || ( shortAmount < 0 )) {
                   ISOException.throwIt(SW_INVALID_TRANSACTION_AMOUNT);
              // check the new balance
              if ((short)( balance + shortAmount)  > MAX_BALANCE) {
                   ISOException.throwIt(SW_EXCEED_MAXIMUM_BALANCE);
              // credit the amount
              balance = (short)(balance + shortAmount);
              return;
         }                                                       // end of deposit method
          * Verify then
          * Update/change pin
          * byte[] bArray is the pin
          * short bOffset is the position in the array the pin starts in the bArray
          * byte bLength is the lenght of the pin
          * @param apdu
         private void updatePin(APDU apdu) {
              //     byte[] bArray, short bOffset, byte bLength){
              //           First check the original pin
              //          verify authentication
              if (! pin.isValidated())
                   ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
              byte[] buffer = apdu.getBuffer();
              // get the number of bytes in the
              // data field of the command APDU -- OFFSET_LC = positon 4
              byte numBytes = buffer[ISO7816.OFFSET_LC];
              // recieve data
              // data are read into the apdu buffer
              // at the offset ISO7816.OFFSET_CDATA
              byte byteRead = (byte)(apdu.setIncomingAndReceive());
              // error if the number of data bytes
              // read does not match the number in the Lc byte
              if (byteRead != numBytes) {
                   ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
              if ( numBytes > 8 )
                   ISOException.throwIt(SW_PIN_TO_LONG);
              if ( numBytes < 4 )
                   ISOException.throwIt(SW_PIN_TO_SHORT);
              short offset_cdata = 05;          
              pin.update(buffer, offset_cdata, numBytes);
              pin.resetAndUnblock();
          *  Admin method
          *  Rest the pin attempts and unblock
          *  @param apdu
         private void adminRest() {
              try {
                   pin.resetAndUnblock();
              } catch (RuntimeException e) {
                   // TODO Auto-generated catch block
              return;
          * Credit loyatly card pints in multiples of 100
          * @param apdu
         private void creditLoyaltyPoints(APDU apdu) {
              short creditAmount = (short) ((loyaltyPoints/ 100) * 100);
              balance = (short) (balance + creditAmount);
              loyaltyPoints = (short) (loyaltyPoints - creditAmount);
              return;
          * Get number of remaining pin tries
          * @param apdu
         private void getPinTriesRemaining(APDU apdu) {
              try {
                   byte[] buffer = apdu.getBuffer();
                   // inform the JCRE that the applet has data to return
                   short le = apdu.setOutgoing();
                   // set the actual number of the outgoing data bytes
                   apdu.setOutgoingLength((byte)2);
                   // write the PinTriesRemaining into the APDU buffer at the offset 0
                   Util.setShort(buffer, (short)0, pin.getTriesRemaining());
                   // send the 2-byte balance at the offset
                   // 0 in the apdu buffer
                   apdu.sendBytes((short)0, (short)2);
              } catch (APDUException e) {
                   // TODO Auto-generated catch block
              } catch (TransactionException e) {
                   // TODO Auto-generated catch block
              } catch (ArrayIndexOutOfBoundsException e) {
                   // TODO Auto-generated catch block
              } catch (NullPointerException e) {
                   // TODO Auto-generated catch block
         } // end of getPinTriesRemaining method
          * No verification needed
          * the method returns the Account’s balance
          * @param apdu
         private void getBalance(APDU apdu) {
              byte[] buffer = apdu.getBuffer();
              // inform the JCRE that the applet has data to return
              short le = apdu.setOutgoing();
              // set the actual number of the outgoing data bytes
              apdu.setOutgoingLength((byte)2);
              // write the balance into the APDU buffer at the offset 0
              Util.setShort(buffer, (short)0, (balance));
              // send the 2-byte balance at the offset
              // 0 in the apdu buffer
              apdu.sendBytes((short)0, (short)2);
          * No verification needed
          * the method returns the Account’s loyaltyPoints balance
          * @param apdu
         private void getLoyaltyPoints(APDU apdu){
              byte[] buffer = apdu.getBuffer();
              // inform the JCRE that the applet has data to return
              short le = apdu.setOutgoing();
              // set the actual number of the outgoing data bytes
              apdu.setOutgoingLength((byte)2);
              // write the loyaltyPoints balance into the APDU buffer at the offset 0
              Util.setShort(buffer, (short)0, (loyaltyPoints));
              // send the 2-byte loyaltyPoints balance at the offset
              // 0 in the apdu buffer
              apdu.sendBytes((short)0, (short)2);
          * No verification needed
          * the method returns the student number
          * @param apdu
         private void getStudentNumber(APDU apdu) {
              byte[] buffer = apdu.getBuffer();
              // inform the JCRE that the applet has data to return
              short le = apdu.setOutgoing();
              // set the actual number of the outgoing data bytes
              apdu.setOutgoingLength((byte)STUDENT_NUMBER_ARRAY.length);
              // write the balance into the APDU buffer at the offset 0
              apdu.sendBytesLong(STUDENT_NUMBER_ARRAY, (short)0, (short) STUDENT_NUMBER_ARRAY.length);
              //     Util.setShort(buffer, (short)0, STUDENT_NUMBER_ARRAY);
              // send the 2-byte balance at the offset
              // 0 in the apdu buffer
              try {
                   apdu.sendBytes((short)0, (short)STUDENT_NUMBER_ARRAY.length);
              } catch (APDUException e) {
                   // TODO Auto-generated catch block
         } // end of getBalance method
          * Verification method to verify the PIN
          * @param apdu
         private void verify(APDU apdu) {
              byte[] buffer = apdu.getBuffer();
              // receive the PIN data for validation.
              byte byteRead = (byte)(apdu.setIncomingAndReceive());
              // check pin
              // the PIN data is read into the APDU buffer
              // starting at the offset ISO7816.OFFSET_CDATA
              // the PIN data length = byteRead
              if (pin.check(buffer, ISO7816.OFFSET_CDATA,byteRead)
                        == false)
                   ISOException.throwIt(SW_VERIFICATION_FAILED);
         } // end of verify method
    } // end of class AccountEdited by: Raymond.garrett-Dublin on Jun 17, 2009 11:30 PM

  • 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.

Maybe you are looking for

  • New uses for an "extra" G3 Powerbook

    This may seem like a dumb question, but I have an "extra" G3 bronze keyboard Powerbook with OSX (Panther) running on it and I have no idea what to do with it. I upgraded last year to an iBook which I love, but I just can't seem to part with my first

  • Setting bind variables in view objects for LOV

    ADF 11.1.1.1.0 I have two application modules - amCodeTable (contains the code tables) and amLOV (contains the list of values) In amLOV I have a VO aListOfValuesVo (not based on an entity) that runs a query Select * from aTable where userNr = :pBindV

  • Importing GL Data

    Hi , I had completed importing the Financials ( AP and AR ) datas.But in order to import the GL data I had to follow the steps in the installation and configuration documentation.As I understand from the documentation , if I configure these subjects

  • How do I set Force Encryption using PowerShell

    I have to automate the task of setting Force Encryption (within Properties under SQL Server Configuration Manager, Network Configuration, Protocols for MSSQLSERVER). Do you know the PowerShell command to set Force Encryption to Yes? Any help would be

  • Combo Box Calculations

    Is there any way to use the drop down box or "combo box" with numbers in a calculation for another field. ex.  "Combo box1"= 500 , 1000, 2000 and "Text1" calculation should be "Combo box1 - 25" It doesn't seem to recognize the number in "Combo Box1"