Applet sudoku

Hello, I was wondering if anyone can help me. I am designing a sudoku game for a project in uni and im struggling to use applets. The difficulty im having now is that i have paint drawing each small grid(as a colored area in the background), but I am using a for loop to create each individual jtextfield for input and within paint it causes issues. Is their a way I can create the painted background for the smaller grids and then add the jtextfields over this outside of paint?
Also any links for good applet tutorials welcome,
cheers in advance
MM

ok, im lost again:)
This is the code i have to give you an idea what im attempting to do, is this the completely wrong way to do this?
public class sudoku extends Applet {
        int row[];
        int column[];
        JTextField game[][];
        JTextField f;
        JTextField n;
        JButton start;
     public void init() {          
          game=new JTextField[9][9];
     public void paint(Graphics g)
          super.paint(g);
          g.setColor(new Color(185, 220, 250));
          g.fillRect(0,0,115,115);
          g.fillRect(235,0,115,115);
          g.fillRect(115,115,120,120);
          g.fillRect(0,235,115,115);
          g.fillRect(235,235,115,115);
          g.setColor(new Color(127, 203, 250));
          g.fillRect(115,0,120,115);
          g.fillRect(0,115,115,120);
          g.fillRect(235,115,115,120);
          g.fillRect(115,235,120,115);
          setLayout(null);
          int row=5;
          int col=5;
          int watcher=0;
          for(int i=0; i<game.length;i++)
               for(int j=0; j<game.length; j++)
                    if(watcher==8)
                         game[i][j]=new JTextField(""+ Integer.toString(i) +""+ Integer.toString(j) +"");
                         game[i][j].setBounds(row,col,20,20);
                         add(game[i][j]);
                         row=5;
                         col=col+40;
                         watcher=0;
                         System.out.println(" watcher equal 9 "+watcher+" i="+i+" j="+j+" row="+row+" col="+col);
                    else
                         game[i][j]=new JTextField();
                         game[i][j].setBounds(row,col,20,20);
                         add(game[i][j]);
                         row=row+40;
                         watcher++;
                         //System.out.println(" watcher not equal 9 "+watcher+" i="+i+" j="+j+" row="+row+" col="+col);
                         //System.out.println("minigrid   =" +minigrid(i,j));
     start=new JButton("Start");
     start.setBounds(1,370,100,30);
     add(start);
     }Thanks again all!!!
MM

Similar Messages

  • Server setting preventing .jar from being read/executed?

    Hey guys,
    I'm not completely sure this is the correct place to be posting my question, but I have been unable to find a better place for it, so hopefully someone here might be able to help me out.
    Ok.
    I have a signed .jar applet, that runs locally and when hosted on a server on the LAN. It also works when the .jar is hosted on my webspace given by my ISP.
    However, I have a website hosted where, for some reason, the applet fails. Furthermore, it only fails when it is packaged in a .jar archive. When only using .class files it works fine, however because I need to use .jar files in order to sign them this is no longer sufficient. The exception given by the java console is :
    java.lang.ClassNotFoundException: UserInterface.class
         at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
         at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.IOException: open HTTP connection failed:http://www.nickmoores.com/applet/sudoku/UserInterface/class.class
         at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
         at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         ... 7 more
    Exception: java.lang.ClassNotFoundException: UserInterface.class
    When I set the trace level in the java console to 5, the first exception that appears is :
    java.io.FileNotFoundException: http://www.nickmoores.com/applet/sudoku/sudoku.jar
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
         at sun.plugin.PluginURLJarFileCallBack.downloadJAR(Unknown Source) .... etc etc etc
    To me, this indicates that it can't find the .jar. However all the web browsers I have tried manage to find the file at the URL given by the exception (ie http://www.nickmoores.com/applet/sudoku/sudoku.jar), so it is not a simple case of having misplaced the jar or giving the wrong path.
    I made a simple .html page with the following html code :
    <!DOCTYPE HTML PUBLIC
      "-//IETF//DTD HTML LEVEL 1//EN">
    <HTML>
      <HEAD>
        <TITLE>Blank HTML Level 1 Page</TITLE>
        <META HTTP-EQUIV="Content-Type"
              CONTENT="text/html; charset=utf-8">
      </HEAD>
      <BODY>
         <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" name="SudokuApplet"
                   width="393" height="327"
                   codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0">
              <param name="codebase" value="/applet/sudoku/" />
              <param name="archive" value="sudoku.jar" />
              <param name="code" value="UserInterface.class" />
              <param name="type" value="application/x-java-applet" />
              <comment>
                   <embed name="SudokuAppletFF"
                           archive="sudoku.jar"
                           codebase="http://nickmoores.pwp.blueyonder.co.uk/applet/sudoku/"
                           code="UserInterface.class"
                           width="393"
                           height="327"
                           type="application/x-java-applet"
                           pluginspage="http://java.sun.com/j2se/1.5.0/download.html">
                        <noembed>No Java Support.</noembed>
                   </embed>
              </comment>
         </object>
      </BODY>
    </HTML>I placed this page at my ISP webspace, my local LAN server, and the hosted site where it doesn't work, and put the .jar in the appropriate location on each server.
    As expected, it works everywhere EXCEPT the hosted website. This convinced me that there is a problem on the hosted website that is somehow preventing the .jar archive from being read from object/embed html tags. This seems strange as it manages to read and load .class files fine.
    I have communicated several times with the people who are hosting my site, and they haven't been too helpful so far. I've had several replies along the lines of "Can you try it now? I think it should be working" and "Have you tried testing it on a local site?", so i'm not sure they really know what the issue is.
    So does anyone know what setting on the server would be preventing the .jar from being loaded?
    If anyone wants to see the problem for themselves, the problem occurs at http://www.nickmoores.com/blanktest.html , but it works at http://www.nickmoores.pwp.blueyonder.co.uk . As you will see from the page source, the code is exactly the same, so it must be a server setting causing the problem, right?
    Thanks guys!

    Try this:
    <!--[if !IE]> -->
    <object classid="java:**.class"
    type="application/x-java-applet"
    archive="**.jar"
    height="350" width="550" >
    <param name="code" value="***.class" />
    <!-- For Konqueror -->
    <param name="archive" value="***.jar" />
    <param name="persistState" value="false" />
    </object>
    <!--<![endif]-->
    <!--[if IE]>
    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-windows-i586.cab#Version=1,4,0,0"
    height="350" width="550" >
    <param name="archive" value="***.jar" />
    <param name="code" value="***.class" />
    <param name="persistState" value="false" />
    </object>
    <!--<![endif]-->

  • Cool n free sudoku - Sudokool

    hi friends
    I have developed a game in java which is based on the popular sudoku puzzles.
    U can get the game at
    http://www.koolpages.com/shiraz/Sudokool.zip
    Now the problem is that the game runs only in windows.
    The main game file is an executable jar file.So double click on the file opens the game.
    But in linux the jar files gets opened and shows the archived class files.
    So plz help me ,how can i make the game run in linux ?
    I cannot use applet bcoz the game interacts with the local files for saving records.
    Moreover the java files are not compiling in linux.
    I have recently installed FC4.When i try to compile java files on terminal,it gives the following warning (where i use inheritance)
    eg.
    class now extends JFrame
    $javac now.java
    Warning: The serializable class now does not declare a static final serialVersionUID field of type long
    However the same file works perfectly well when run on Windows.The JVM on FC4 is 1.4.2 and even though i have installed the latest version of gcc(4.0.1)the problem still persists
    Plz help me...

    Have you thought about generating solutions?During my extensive mind travelling in the future I've noted that Sudoku has replaced the Eight Queen problem as next year's favourite homework assignment. This forum was completely flooded with queries from desperate newbies and only a heroic round-the-clock effort from all regulars could hold the reputation up of this forum as the number one homework cheating place. Thank you all for your future effort.

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

  • Open web pages from an applet

    I'm developing an applet that has to open some web pages.
    The only way I know is to use the method showDocument that
    needs and URL. So, how to pass parameters to the web page?
    I don't want to put them in the URL: everyone can see
    "secret data"!
    Help me, please.

    Take a look at this example that uses a JEditor pane to hold the HTML page.
    //Create a new JEditor Pane
    jep = new JEditorPane( );
    //Ensure the pane is not editable
    jep.setEditable(false);  
    //Use this to get local HTML file
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");
    //add the html page to the JEditorPane
    jep.setPage(fileURL);Ok the core line of code here is this.
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");The standard method for accessing a html file via a URL is thus. As you can see its very similar.
    URL fileURL = new URL("http://www.comp.glam.ac.uk/pages/staff/asscott/progranimate/docs/Manual/Manual.htm");this.getClass().getResourse() will return the file location of the class you are working with.
    By doing the following you can access manual.html in a folder called Manual that sits in the same file location as the class file you are using.
    URL fileURL = this.getClass().getResource("Manual/Manual.htm");I hope this helps.
    Andrew.

  • Unable to load database driver from my applet's jar file

    I'm trying to set up an applet that will talk to a MySQL database. I have no problem connecting to the database as I'm developing the code ("un-jarred"), but when I create a jar file of my code to test through a web browser, I cannot connect to the database due to the usual ClassNotFoundException. I have included mysql-connector-java-3.1.12-bin.jar (the current driver) in the jar, but I don't know if I'm supposed to supply some info through an attribute to the applet tag to let it know that the jar contains the driver it needs or if I have to call the driver differently in my code.
    Any help is appreciated, thanks.

    The simplest approach is always the best. :)Abso-lutely.
    Awesome, that worked perfectly. I Included the extra
    jar file in the applet tag and now my applet makes
    some sweet lovin' to the database.And you have succeeded where thousands have failed. Congratulations.

  • Applet java file not refreshing in browser

    I have an applet that I am updating and I am not seeing the corresponding update when I open the web page. I can manually download the java class file and look inside it and it definitely is the updated file. I have deleted the browser history. (I am running tests with Firefox 3, IE7, and Safari 4 public beta). Is there something else I need to do to make sure the browser pulls in the latest version of the class file referenced in the html?
    Here is the code:
    <HTML>
    <HEAD>
       <TITLE>A Simple Program</TITLE>
    </HEAD>
    <BODY>
       <CENTER>
          <APPLET CODE="SendRequest.class" WIDTH="500" HEIGHT="150">
          </APPLET>
       </CENTER>
    </BODY>
    </HTML>The applet refers to a hard coded URL to read through a urlconnection. It is always reading a file and showing content, but it is not showing the right file. If I change the name of the referenced file in the java program, it looks like the browser has cached the referred file, rather than throwing and error and saying the file doesn't exist.
    Here is the java
    import java.applet.*;
    import java.awt.*;
    import java.net.URLConnection;
    import java.net.URL;
    import org.w3c.dom.Document;
    import java.lang.String;
    import java.io.*;
    public class SendRequest extends Applet {
        @Override
        public void paint(Graphics g) {
            g.drawRect(0, 0, 499, 149);
            g.drawString(getResponseText(), 5, 70);
        public String getResponseText() {
            try {
                URL url = new URL("http://myserver.com/stats/logs/ex20090603000001-72.167.131.217.log");
                URLConnection urlconn = url.openConnection();
                BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    urlconn.getInputStream()));
                String inputLine;
                String htmlFile = "";
                try {
                    while ((inputLine = in.readLine()) != null)
                        htmlFile += inputLine;
                    in.close();
                    return htmlFile;
                } catch (Exception e) {
                    return "Can't get the string.";
            } catch (Exception e) {
                return "Problem accessing the response text.";
    }Any help would be appreciated. I heard that some files may cache more persistently than others, but I don't fully understand the details.
    Thanks,
    Jim

    Check this [document loader example|http://pscode.org/test/docload/] & follow the link to sandbox.html for tips on clearing the class cache. That relates specifically to caching a refused security certificate, but class caching is much the same. As an aside, getting a console can be tricky in modern times (unless the applet fails completely). It is handy to configure the [Java Control Panel|http://java.sun.com/docs/books/tutorial/information/player.jnlp] to pop the Java console on finding an applet (Advanced tab - Settings/Java Console/Show Console).
    Of course there are two better tools for testing applets, especially in regard to class caching. AppletViewer and Appleteer both make class refresh fairly easy. Appleteer is the better of the two. I can tell you that with confidence, since I wrote it. ;-)

  • Looking for All-In-One Sudoku Game App for iPad?

    Bare with me...  I'm going to learn now if this is an appropriate question here and if not where to go that would be appropriate?
    I'm looking for a great iPad Sudoku game app that offers a variety of different format variations using numbers 1-9, different colors, and different shapes--that sort of thing...instead of just the common numbers.  I'm not concerned about scoring the game or tracking time or the leaderboard stuff.
    I've looked and found a gillion to consider including Google and looked at some for more detail but so far have found none...and maybe none exist or maybe I'll have to settle for two or three separate Sudoku games to fullfill what I'm after?
    So maybe someone in the community knows of just the Sudoku app I'm looking for?
    Thank you.

    A quick Google search provided the following:  http://itunes.apple.com/us/app/sudoku-hd-for-ipad/id364909963?mt=8
    I don't know if it offers exactly what you want, but you can check the App Store, or you can go to Google and type the following in your search bar:  apple sodoku app ipad
    Several options will come up.

  • EJB 3.0 - Communicate an Applet with a Session Bean

    Hello
    I'm developing an EJB 3.0 app (eclipse and glassfish tools bundle), and I have an applet that has to use remote session beans.
    QUESTION: Is it possible for the applet to connect to EJB?
    QUESTION: By creating a J2EE application client project, can I use @EJB annotations to inject the session bean directly to the applet, avoiding the JNDI lookup?
    (since I imagine that the anwser to the second one is NO, I do the following consideration)
    Given an application client project, I imagine that this application can run remotely on a client machine/JRE. Then this application can use Annotations/injection facilities whenever it runs on a J2EE client container (which I assume consists of a set of libraries provided by the application server vendor, Glassfish in that case). Could this application be deployed using Java Web Start? If so, why can't it be deployed as an applet? (both options run in a client JRE, don't they?).
    QUESTION: In either case (applet or JWS), how do I have to package the JAR file (using Eclipse) so that it contains the needed libraries for accessing the EJB? Which are those libraries?
    At the time being, I'm trying to implement a sample application that follows the "Applet doing JNDI lookup" approach. I have:
    - an EAR project
    - an EJB project (containing an Entity Bean and a Stateless Session Bean with a @Remote interface)
    @Remote
    public interface HelloRemote {
         public String hello(String name);
    @Stateless
    public class Hello implements HelloRemote {
         @Override
         public String hello(String name) {
              return "Hello "+name+"!!";
    }- an Application Client project (containing the applet code):
    public class ClientApplet extends JApplet {
         public void init(){     
              try {
                   Context jndiContext = getInitialContext( );
                   HelloRemote server = (HelloRemote) jndiContext.lookup(HelloRemote.class.getName());
                   setContentPane(new JLabel(server.hello("Gerard")));
              } catch (NamingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         private Context getInitialContext() throws NamingException{
              Properties props = new Properties();
              props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
              props.setProperty("org.omg.CORBA.ORBInitialHost", "myhost");
              props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
              return new InitialContext(props);
    }- a static web project (with a sample web page that contains the applet object the corresponding applet JAR file)
    I tried to export the Application Client project as an "application client JAR", in the hope that the java EE libraries bundled with glassfish (listed as libraries of this project) would be packaged too.
    No success, so now I'll try to copy all the JAR files (one by one) into the +\WebContent\+ folder of the Web Project, and add references to each of them in the archive="" attribute of the +<applet>+ HTML tag. Although this might work, I suspect that I am missing the good/easy way of doing it. Any suggestions?
    Thanks in advance,
    Gerard
    Edited by: gsoldevila on May 6, 2009 7:09 AM

    An Applet can communicate with an EJB via JNDI lookup but I would (personally) use an intermediate Servlet to handle this. Client to Servlet communication is http whereas to ejb is iiop - which might be blocked.
    Injection only works in managed classes (EJB, Servlet, Listeners..) and an Application Client main class. So yes you could use an app client for handling resource injection.
    m

  • Error while accessing a public method of applet from javascript.

    Hi,
    I am getting "Object doesn't support this property or method" error
    when accessing a public method of applet from javascript in IE 6 using
    document.applets[0].myMethod();
    The same is working in IE 7.
    Thanks in advance.
    Regards,
    Phanikanth

    I don't know why it happens, but this works for me in both versions:
    <applet ..... name="MyApplet">
    </applet>and in javascript use
    document.MyApplet.myMethod()

  • Can not view applet in browser (IE5.5)

    only my appletviewer shows my very simple applet.
    in the IE5.5 i can not view my applet... ?
    my applet just have write a string...
    any help ?

    http://forum.java.sun.com/thread.jsp?forum=31&thread=276607

  • A function can not be used in Applet.what's wrong?

    Here is a function.
    private String LoadFile() {
    String input;
    String output="sssssdsdsddf";
    try{
    FileReader f=new FileReader("shu.txt");
    BufferedReader in = new BufferedReader(f);
    while ((input = in.readLine())!= null){output=output+input;}
    in.close();
    }catch(IOException e) {
    System.err.println("Exception caught: " + e.getMessage());
    return output;
    It can be used in Java Application,and work well.but can not be used in Applet,it does not work.what's wrong?

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1215-security.html#sidebar1

  • A function can not be used in Applet.what' wrong?

    Here is a function.
              private String LoadFile() {
    String input;
              String output="sssssdsdsddf";
              try{
              FileReader f=new FileReader("shu.txt");
    BufferedReader in = new BufferedReader(f);
    while ((input = in.readLine())!= null){output=output+input;}
              in.close();
              }catch(IOException e) {   
                   System.err.println("Exception caught: " + e.getMessage());
    return output;
    It can be used in Java Application,and work well.but can not be used in Applet,it does not work.what's wrong?

    Don't you think it would be a bit of a security risk if any applet you downloaded from the web (unknowingly) could read/write to your file system....
    Applets have strict security applied to them, and file i/o is one of the restrictions. There are ways around it, but for the moment I'd suggest you build a bridge and get over it.
    Cheers,
    Radish21

  • Unable to delete applet.....

    Hi all,
    I am unable to delete one applet which I have loaded in the card.
    There are 2 applets, one is purse and other is loyalty. And am using shareable interface in which loyalty is the server and purse is the client. I can delete the purse applet but i can't delete the loyalty from the card.
    Here is my code : There are in all 3 codes, one is purse, second is loyalty code and third is the shareable interface code. Can some one look at the code and tell me what's wrong in this programs.
    package com.gemplus.examples.loyalty;
    import javacard.framework.*;
    import visa.openplatform.*;
    public class Loyalty extends javacard.framework.Applet implements TestInterface
    static byte points ;
    protected Loyalty(byte[] buffer, short offset, byte length)
    // data offset is used for application specific parameter.
    // initialization with default offset (AID offset).
    short dataOffset = offset;
    if(length > 9) {
    // Install parameter detail. Compliant with OP 2.0.1.
    // | size | content
    // |------|---------------------------
    // | 1 | [AID_Length]
    // | 5-16 | [AID_Bytes]
    // | 1 | [Privilege_Length]
    // | 1-n | [Privilege_Bytes] (normally 1Byte)
    // | 1 | [Application_Proprietary_Length]
    // | 0-m | [Application_Proprietary_Bytes]
    // shift to privilege offset
    dataOffset += (short)(1 + buffer[offset]);
    // finally shift to Application specific offset
    dataOffset += (short)(1 + buffer[dataOffset]);
    // checks wrong data length
    if(buffer[dataOffset] != 4)
    // return received proprietary data length in the reason
    ISOException.throwIt((short)(ISO7816.SW_WRONG_LENGTH + offset + length - dataOffset));
    // go to proprietary data
    dataOffset++;
    // points = 0;
    // register this instance
    register(buffer, (short)(offset + 1), (byte)buffer[offset]);
    * Method installing the applet.
    * @param bArray the array constaining installation parameters
    * @param bOffset the starting offset in bArray
    * @param bLength the length in bytes of the data parameter in bArray
    public static void install(byte[] bArray, short bOffset, byte bLength) throws ISOException
    /* applet instance creation */
    new Loyalty (bArray, bOffset, (byte)bLength);
    * Select method returning true if applet selection is supported.
    * @return boolean status of selection.
    public boolean select()
    /* return status of selection */
    return true;
    * Deselect method.
    public void deselect()
    return;
    public void process(APDU apdu) throws ISOException
              // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
              ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
                   apdu.setIncomingAndReceive();
              byte[] apduBuffer = apdu.getBuffer();
    // writes the balance into the APDU buffer after the APDU command part
              creditPoints((byte)0x00);     
              apduBuffer[5] = (byte)(points >> 8) ;
              apduBuffer[6] = (byte)points ;
    // sends the APDU response
    // switches to output mode
              apdu.setOutgoing() ;
    // 2 bytes to return
              apdu.setOutgoingLength((short)2) ;
    // offset and length of bytes to return in the APDU buffer
              apdu.sendBytes((short)5, (short)2) ;
         public void creditPoints(byte pTobeCredited)
    points += pTobeCredited;
    public Shareable getShareableInterfaceObject(AID client, byte param){
              if(param != (byte)0x00)
                   return null;
         return (this);
    second code is :
    package com.gemplus.examples.oppurse;
    * Imported packages
    import javacard.framework.*;
    import visa.openplatform.*;
    import com.gemplus.examples.loyalty.*;
    public class OPPurse extends javacard.framework.Applet
    // the APDU constants for all the commands.
         private final static byte INS_GET_BALANCE = (byte)0x30 ;
         private final static byte INS_DEBIT      = (byte)0x31 ;
         private final static byte INS_CREDIT      = (byte)0x32 ;
         private final static byte INS_VERIFY_PIN = (byte)0x33 ;
         private final static byte INS_SET_NAME                    = (byte)0x34 ;
         private final static byte INS_GET_NAME                    = (byte)0x35 ;
    // the OP/VOP specific instruction set for mutual authentication
         private final static byte CLA_INIT_UPDATE = (byte)0x80 ;
         private final static byte INS_INIT_UPDATE = (byte)0x50 ;
         private final static byte CLA_EXTERNAL_AUTHENTICATE = (byte)0x84 ;
         private final static byte INS_EXTERNAL_AUTHENTICATE = (byte)0x82 ;
    // the PIN validity flag
    private boolean validPIN = false;
    // SW bytes for PIN Failed condition
         // the last nibble is replaced with the number of remaining tries
         private final static short      SW_PIN_FAILED = (short)0x63C0;
         private final static short SW_FAILED_TO_OBTAIN_SIO = (short)0x63D0;
         private final static short SW_LOYALTY_APP_NOT_EXIST = (short)0x63E0;
    // the illegal amount value for the exceptions.
    private final static short ILLEGAL_AMOUNT = 1;
    // the maximum balance in this purse.
    private static final short maximumBalance = 10000;
    // the current balance in this purse.
    private static short balance;
    /*     byte[] loyaltyAID = new byte[]{ (byte)0xA0,(byte)0x00,(byte)0x00,(byte)0x00,
              (byte)0x19,(byte)0xFF,(byte)0x00,(byte)0x00,
              (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,
              (byte)0x00,(byte)0x00,(byte)0x02,(byte)0x02};*/
    /* Security part of declarations */
    // the Security Object necessary to credit the purse
    private ProviderSecurityDomain securityObject = null;
    // the security channel number
    byte secureChannel = (byte)0xFF;
    // the authentication status
    private boolean authenticationDone = false;
    // the secure channel status
    private boolean channelOpened = false;
         private byte[] nameBuffer = new byte[6];
    * Only this class's install method should create the applet object.
    protected OPPurse(byte[] buffer, short offset, byte length)
    // data offset is used for application specific parameter.
    // initialization with default offset (AID offset).
    short dataOffset = offset;
    if(length > 9) {
    // Install parameter detail. Compliant with OP 2.0.1.
    // | size | content
    // |------|---------------------------
    // | 1 | [AID_Length]
    // | 5-16 | [AID_Bytes]
    // | 1 | [Privilege_Length]
    // | 1-n | [Privilege_Bytes] (normally 1Byte)
    // | 1 | [Application_Proprietary_Length]
    // | 0-m | [Application_Proprietary_Bytes]
    // shift to privilege offset
    dataOffset += (short)( 1 + buffer[offset]);
    // finally shift to Application specific offset
    dataOffset += (short)( 1 + buffer[dataOffset]);
    // checks wrong data length
    if(buffer[dataOffset] != 2)
    // return received proprietary data length in the reason
    ISOException.throwIt((short)(ISO7816.SW_WRONG_LENGTH + offset + length - dataOffset));
    // go to proprietary data
    dataOffset++;
    } else {
    // Install parameter compliant with OP 2.0.
    if(length != 2)
    ISOException.throwIt((short)(ISO7816.SW_WRONG_LENGTH + length));
              // retreive the balance value from the APDU buffer
    short value = (short)(((buffer[(short)(dataOffset + 1)]) & 0xFF)
              | ((buffer[dataOffset] & 0xFF) << 8));
    // checks initial balance value
    if(value > maximumBalance)
    ISOException.throwIt(ISO7816.SW_DATA_INVALID);
              // initializes the balance with the APDU buffer contents
    balance = value;
    // register this instance as an installed Applet
    register();
    // ask the system for the Security Object associated to the Applet
    securityObject = OPSystem.getSecurityDomain();
    // applet is personalized and its state can change
    OPSystem.setCardContentState(OPSystem.APPLET_PERSONALIZED);
    // build the new ATR historical bytes
    byte[] newATRHistory = new byte[]
    // put "OPPurse" in historical bytes.
    (byte)0x4F, (byte)0x50, (byte)0x50, (byte)0x75, (byte)0x72, (byte)0x73, (byte)0x65
    // !!! ACTIVATED IF INSTALL PRIVILEGE IS "Default Selected" (0x04). !!!
    // change the default ATR to a personalized's one
    OPSystem.setATRHistBytes(newATRHistory, (short)0, (byte)newATRHistory.length);
    * Method installing the applet.
    * @param installparam the array constaining installation parameters
    * @param offset the starting offset in installparam
    * @param length the length in bytes of the data parameter in installparam
    public static void install(byte[] installparam, short offset, byte length )
    throws ISOException
    // applet instance creation with the initial balance
    new OPPurse(installparam, offset, length );
    * Select method returning true if applet selection is supported.
    * @return boolean status of selection.
    public boolean select()
    validPIN = false;
    // reset security if used.
    // In case of reset deselect is not called
    reset_security();
    // return status of selection
    return true;
    * Deselect method.
    public void deselect()
    // reset security if used.
    reset_security();
    return;
    * Method processing an incoming APDU.
    * @see APDU
    * @param apdu the incoming APDU
    * @exception ISOException with the response bytes defined by ISO 7816-4
    public void process(APDU apdu) throws ISOException
    // get the APDU buffer
    // the APDU data is available in 'apduBuffer'
    byte[] apduBuffer = apdu.getBuffer();
    // the "try" is mandatory because the debit method
    // can throw a javacard.framework.UserException
    try
         switch(apduBuffer[ISO7816.OFFSET_INS])
    case INS_VERIFY_PIN :
         verifyPIN(apdu);
    break ;
    case INS_GET_BALANCE :
         getBalance(apdu) ;
    break ;
    case INS_DEBIT :
         debit(apdu) ;
    break ;
                        case INS_SET_NAME :
                             setName(apdu);
                        break;
                        case INS_GET_NAME :
                             getName(apdu);
                        break ;
    case INS_CREDIT :
         credit(apdu) ;
    break ;
    case INS_INIT_UPDATE :
    if(apduBuffer[ISO7816.OFFSET_CLA] == CLA_INIT_UPDATE)
    // call initialize/update security method
         init_update(apdu) ;
    else
    // wrong CLA received
    ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
    break ;
    case INS_EXTERNAL_AUTHENTICATE :
    if(apduBuffer[ISO7816.OFFSET_CLA] == CLA_EXTERNAL_AUTHENTICATE)
    // call external/authenticate security method
         external_authenticate(apdu) ;
    else
    // wrong CLA received
    ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
    break ;
    case ISO7816.INS_SELECT :
    break ;
    default :
    // The INS code is not supported by the dispatcher
         ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED) ;
    break ;
         }     // end of the switch
    } // end of the try
              catch(UserException e)
    // translates the UserException in an ISOException.
              if(e.getReason() == ILLEGAL_AMOUNT)
    throw new ISOException ( ISO7816.SW_DATA_INVALID ) ;
    //- P R I V A T E M E T H O D S -
         * Handles Verify Pin APDU.
         * @param apdu APDU object
         private void verifyPIN(APDU apdu)
    // get APDU data
              apdu.setIncomingAndReceive();
    // get APDU buffer
    byte[] apduBuffer = apdu.getBuffer();
    // check that the PIN is not blocked
    if(OPSystem.getTriesRemaining() == 0)
    OPSystem.setCardContentState(OPSystem.APPLET_BLOCKED);
    // Pin format for OP specification
    // |type(2),length|nible(1),nible(2)|nible(3),nible(4)|...|nible(n-1),nible(n)|
    // get Pin length
    byte length = (byte)(apduBuffer[ISO7816.OFFSET_LC] & 0x0F);
    // pad the PIN ASCII value
    for(byte i=length; i<0x0E; i++)
    // only low nibble of padding is used
    apduBuffer[ISO7816.OFFSET_CDATA + i] = 0x3F;
    // fill header TAG
    apduBuffer[0] = (byte)((0x02 << 4) | length);
    // parse ASCII Pin code
    for(byte i=0; i<0x0E; i++)
    // fill bytes with ASCII Pin nibbles
    if((i & 0x01) == 0)
    // high nibble
    apduBuffer[(i >> 1)+1] = (byte)((apduBuffer[ISO7816.OFFSET_CDATA + i] & 0x0F) << 4);
    else
    // low nibble
    apduBuffer[(i >> 1)+1] |= (byte)(apduBuffer[ISO7816.OFFSET_CDATA + i] & 0x0F);
    // verify the received PIN
    // !!! WARNING PIN HAS TO BE INITIALIZED BEFORE USE !!!
    if(OPSystem.verifyPin(apdu, (byte)0))
    // set PIN validity flag
    validPIN = true;
    // if applet state is BLOCKED then restore previous state (PERSONALIZED)
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
    OPSystem.setCardContentState(OPSystem.APPLET_PERSONALIZED);
    return;
         // the last nibble of returned code is the number of remaining tries
              ISOException.throwIt((short)(SW_PIN_FAILED + OPSystem.getTriesRemaining()));
    * Performs the "getBalance" operation on this counter.
    * @param apdu The APDU to process.
    private void getBalance( APDU apdu )
    // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
                   ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
    // get the APDU buffer
    byte[] apduBuffer = apdu.getBuffer();
    // writes the balance into the APDU buffer after the APDU command part
              apduBuffer[5] = (byte)(balance >> 8) ;
              apduBuffer[6] = (byte)balance ;
    // sends the APDU response
    // switches to output mode
              apdu.setOutgoing() ;
    // 2 bytes to return
              apdu.setOutgoingLength((short)2) ;
    // offset and length of bytes to return in the APDU buffer
              apdu.sendBytes((short)5, (short)2) ;
         private void setName(APDU apdu)
              // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
                   ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
              // the operation is allowed only if master pin is validated
         if(!validPIN)
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
              byte[] apduBuffer = apdu.getBuffer();
              apdu.setIncomingAndReceive();     
              for(short i=0,k=5;i<6;i++,k++)
                   nameBuffer[i] = apduBuffer[k];
         }//end of setName
         private void getName(APDU apdu)
              // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
                   ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
                   byte[] apduBuffer = apdu.getBuffer();
                   for(short i=5, k=0;i<11;i++,k++)
                        apduBuffer=nameBuffer[k];
                   apdu.setOutgoing();
                   apdu.setOutgoingLength((short)6);
                   apdu.sendBytes((short)5,(short)6);
         }//end of storeName
    * Performs the "debit" operation on this counter.
    * @param apdu The APDU to process.
    * @exception ISOException If the APDU is invalid.
    * @exception UserException If the amount to debit is invalid.
    private void debit(APDU apdu) throws ISOException, UserException
    // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
                   ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
    // the operation is allowed only if master pin is validated
         if(!validPIN)
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    // get the APDU buffer
    byte[] apduBuffer = apdu.getBuffer();
         // Gets the length of bytes to recieved from the terminal and receives them
    // If does not receive 4 bytes throws an ISO.SW_WRONG_LENGTH exception
              if(apduBuffer[4] != 2 || apdu.setIncomingAndReceive() != 2)
              ISOException.throwIt(ISO7816.SW_WRONG_LENGTH) ;
              // Reads the debit amount from the APDU buffer
    // Starts at offset 5 in the APDU buffer since the 5 first bytes
    // are used by the APDU command part
              short amount = (short)(((apduBuffer[6]) & (short)0x000000FF)
    | ((apduBuffer[5] << 8 ) & (short)0x0000FF00));
    // tests if the debit is valid
    if((balance >= amount) && (amount > 0))
    // does the debit operation
    balance -= amount ;
    // writes the new balance into the APDU buffer
    // (writes after the debit amount in the APDU buffer)
    apduBuffer[7] = (byte)(balance >> 8) ;
    apduBuffer[8] = (byte)balance ;
    // sends the APDU response
    apdu.setOutgoing() ; // Switches to output mode
    apdu.setOutgoingLength((short)2) ; // 2 bytes to return
    // offset and length of bytes to return in the APDU buffer
    apdu.sendBytes((short)7, (short)2) ;
              /*short points = 10;
    AID loyaltyID = JCSystem.lookupAID(loyaltyAID, (short)0, (byte)loyaltyAID.length);
              if(loyaltyID == null)
                   ISOException.throwIt((short)(SW_LOYALTY_APP_NOT_EXIST));
              TestInterface sio = (TestInterface)(JCSystem.getAppletShareableInterfaceObject(loyaltyID, (byte)0x00));
              if(sio == null)
                   ISOException.throwIt((short)(SW_FAILED_TO_OBTAIN_SIO));
              sio.creditPoints(points);*/
    else
    // throw a UserException with illegal amount as reason
    throw new UserException(ILLEGAL_AMOUNT) ;
    /* byte points = (byte)0x0A;
              //short points = 10;
    AID loyaltyID = JCSystem.lookupAID(loyaltyAID, (short)0, (byte)loyaltyAID.length);
              if(loyaltyID == null)
                   ISOException.throwIt((short)(SW_LOYALTY_APP_NOT_EXIST));
              TestInterface sio = (TestInterface)JCSystem.getAppletShareableInterfaceObject(loyaltyID, (byte)0x00);
              if(sio == null)
                   ISOException.throwIt((short)(SW_FAILED_TO_OBTAIN_SIO));
              sio.creditPoints(points);*/
    * Performs the "credit" operation on this counter. The operation is allowed only
    * if master pin is validated
    * @param apdu The APDU to process.
    * @exception ISOException If the APDU is invalid or if the amount to credit
    * is invalid.
    private void credit(APDU apdu) throws ISOException
    // check valid Applet state
    if(OPSystem.getCardContentState() == OPSystem.APPLET_BLOCKED)
                   ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
    // the operation is allowed only if master pin is validated and authentication is done
         if (!validPIN || !authenticationDone)
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    // get the APDU buffer
    byte[] apduBuffer = apdu.getBuffer();
              // gets the length of bytes to recieved from the terminal and receives them
    // if does not receive 2 bytes throws an ISO.SW_WRONG_LENGTH exception
              if(apduBuffer[4] != 2 || apdu.setIncomingAndReceive() != 2)
    throw new ISOException(ISO7816.SW_WRONG_LENGTH) ;
              // reads the credit amount from the APDU buffer
    // starts at offset 5 in the APDU buffer since the 5 first bytes
    // are used by the APDU command part
              short amount = (short)(((apduBuffer[6]) & (short)0x000000FF)
    | ((apduBuffer[5] << 8) & (short)0x0000FF00));
    // tests if the credit is valid
    if(((short)(balance + amount) > maximumBalance) || (amount <= (short)0))
    throw new ISOException(ISO7816.SW_DATA_INVALID) ;
    else
    // does the credit operation
    balance += amount ;
    * Performs the "init_update" security operation.
    * @param apdu The APDU to process.
    private void init_update( APDU apdu )
    // receives data
    apdu.setIncomingAndReceive();
    // checks for existing active secure channel
    if(channelOpened)
    // close the openned security channel
    try
    securityObject.closeSecureChannel(secureChannel);
    catch(CardRuntimeException cre2)
    // channel number is invalid. this case is ignored
    // set the channel flag to close
    channelOpened = false;
    try
    // open a new security channel
    secureChannel = securityObject.openSecureChannel(apdu);
    // set the channel flag to open
    channelOpened = true;
    // get expected length
    short expected = apdu.setOutgoing();
    // send authentication result
    // expected length forced to 0x1C
    apdu.setOutgoingLength((byte)0x1C);
    apdu.sendBytes(ISO7816.OFFSET_CDATA, (byte)0x1c);
    catch(CardRuntimeException cre)
    // no available channel or APDU is invalid
    ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    * Performs the "external_authenticate" security operation.
    * @param apdu The APDU to process.
    private void external_authenticate( APDU apdu )
    // receives data
    apdu.setIncomingAndReceive();
    // checks for existing active secure channel
    if(channelOpened)
    try
    // try to authenticate the client
    securityObject.verifyExternalAuthenticate(secureChannel, apdu);
    // authentication succeed
    authenticationDone = true;
    catch(CardRuntimeException cre)
    // authentication fails
    // set authentication flag to fails
    authenticationDone = false;
    // close the openned security channel
    try {
    securityObject.closeSecureChannel(secureChannel);
    } catch(CardRuntimeException cre2) {
    // channel number is invalid. this case is ignored
    // set the channel flag to close
    channelOpened = false;
    // send authentication result
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    // send authentication result
    ISOException.throwIt(ISO7816.SW_NO_ERROR);
    else
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    * The "reset_security" method close an opened secure channel if exist.
    * @return void.
    public void reset_security()
    // close the secure channel if openned.
    if(secureChannel != (byte)0xFF)
    try
    // close the openned security channel
    securityObject.closeSecureChannel(secureChannel);
    catch(CardRuntimeException cre2)
    // channel number is invalid. this case is ignored
    // reset security parameters
    secureChannel = (byte)0xFF;
    channelOpened = false;
    authenticationDone = false;
    return;
    and the 3rd code is:
    package com.gemplus.examples.loyalty;
    import javacard.framework.Shareable;
    public interface TestInterface extends Shareable
    // public void creditPoints(byte points) ;
              public void creditPoints(byte points) ;
    Thanks in advance......

    Thanks. I know they are not the same thing. A package cannot be deleted if it contains one or more applets.
    I tried to delete by typing in the applet AID first, but it just doesn't work. And of course it doesn't work for package AID.
    Both the package and applet AID are generated in JBuilder, which looks like this, package AID(6D 79 70 61 63 6B 61 67 31),
    applet AID(6D 79 70 61 63 30 30 30 31),
    instance AID(6D 79 70 61 63 30 30 30 31)
    I've tried those three AIDs, it's not working.
    Thanks.

  • Applet load times got you down?

    Then vote for this RFE:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6346341
    The whole discussion started here:
    http://forum.java.sun.com/thread.jspa?threadID=678853&tstart=0
    -Dennis

    I have the same problem, and add this replay to motivate a clever person to solve this problem.
    My situation is:
    20 Applets (or so) on one page - they span exactly on Thread - if clicked. And if I reload the page they never work again - I have to restart the browser.
    If I browse to the page with the applets I have complete browser crash in 3 of 4 cases. But the first time I visted the page after reboot of Linux (everything less don't help) all the applets work.
    If I put only one Applet on a page and reload this page, then in a few lucky cases the Applet works a second time.
    On windows everything is fine, so I don't think my
    Applets are the problem.
    On linux I tried several version of upto Mozilla 0.9.8
    everytime the same (but 0.9.8 don't work at all with the plugin).

Maybe you are looking for

  • Error while creating external alias for BSPs & DMS

    Hello All, Has anybody encountered the below error dump while creating the external aliases for Business Server Pages and Document Management Service? The error dump I have received is "ITAB_DUPLICATE_KEY" "A Row with same key already exists" The err

  • Why does my cursor arrow refuse to open links.  The arrow changes to the text bar

    When I have links or boxs that tell me to check them to opne something or go somewhere else, my cursor arrow, when I move it over the print, changes to the text bar that shows where my curcsor is within text.  Then nothing happens when I click on the

  • How to get past gray screen on MacBook?

    How to get past gray screen on MacBook?

  • Westmere Graphic Card

    Hi, this might be a more "average user" kind of question to some of you, but...: Does anyone here happen to know, which graphic card is the best choice for the westmere (6x3,33), if you're working with adobe production premium - so for using cuda / m

  • Installing Leopard

    So ive finally got it. Still sitting in its wrapping though as im a bit unsure as to whether to install it as there seems to be a lot of problems with it and performance issues, what is the best way to install it?? From fresh or do i archive?? Dont f