HELP Extending JAASAuthentication Example with JSC

Hi All,
Does anyone out there know how to go about extending the JAASAuthentication example shipped with JSC to include Authorisation code (for example, using roles)? I have managed to successfully swap out the use of the Derby database with that of a mySQL 5.0 database and would like to extend the database and the example app to include provision for user roles within the system so that I can protect say an admin area. I am really new to both JSC and JAAS and could really do with a little bit of help. I'm concerned that if I just search the web looking for clues that I will not end up using a best practice solution.
If anyone from sun reads this post it would have been great if you had included even just a simple example of Authorisation as well as Authentication with this sample app, I think it would have enabled lots of people to get a real head start into building web apps with JSC.
Kind Regards,
Paul Anderson

Hi,
you should look towards jguard (http://www.jguard.net) which enable easy JAAS integration into webapps with multiple databases.
it integrates many featuers including taglibs to protect frmagents of page, authentication, authorization,role inheritance and so on... ...
hope it helps,
Charles.
jGuard team.

Similar Messages

  • Has anyone a jasper 6.8 example that works fine with JSC/JSF ???

    Has anyone just a jasper 6.8 example that works fine with JSC 2 / JSF ???
    Because I tried everything and it still doesn't want to do anything, and the code provided in this forum : http://swforum.sun.com/jive/thread.jspa?threadID=50166&tstart=0 doesn't work will other files or other than 6.1 Jasper version.
    thanks a lot
    Pierre

    Thank you for your answer, but this is exactly the thread I used and that I mentionned in my first message !!!
    this jasper example works fine with Creator only with the provided jasper file and the provided library. If I try to compile the jrxml provided, to change the library and so on, it doesn't work anymore, I don't know why.
    On this thread you can see more details :
    http://sourceforge.net/forum/forum.php?thread_id=1311641&forum_id=113530
    thanks for your help,
    Pierre

  • In Data Quality transform please explain Associate transform with the help of any example.

    In Data Quality transform please explain Associate transform with the help of any example.

    Hi Neha,
    If we are using multiple match transforms and consolidate the final output we will use associate transform .
    Let me explain with one example based on data quality blue prints for USA .
    We have customer/vendor data .     We need to find the duplicates .
    1. First  we will find the duplicates  on   Name and Address
    2. Second  we will find the duplicates on Name and Email
    3. Third we will find the duplicates on Name and Phone
    Here why we need to find the duplicates in multiple stages . If we are finding the duplicates on combination of  Name, Address, Email and Phone  we may not get proper duplicates   as we are finding the potential duplicates . That's why we are finding the duplicates on different combinations .
    In this case we will get the different group numbers for each match combination . Each combination name is there .
    We want to consolidate and give the group number to the whole set of duplicates . We will pass these  3 match groups to associative transform and generate the  consolidated match group for the input data.
    I hope you understand the concept .
    Thanks & Regards,
    Ramana.

  • Extended access list with multiple ports

    Hello All,
    I have a problem with my Cisco Catalyst 4503-E when i try to configure an extended access lists with multipleports.
    I receive the following message:
    The informations of my Switch are the following:
    Cisco IOS Software, Catalyst 4500 L3 Switch Software (cat4500-IPBASE-M), Version
    12.2(52)SG, RELEASE SOFTWARE (fc1)
    Please help me to resolve this problem.
    Best regards.

    Thank you Alex for your response.
    Yes, this is an example:
    permit tcp 192.168.1.0 0.0.0.255 host 192.168.2.1 eq 135 389 636 445 3268 3269 domain 88
    I have more ACLs and each ACL contains more conditions with multiples Por

  • Toplink 9.0.3 can't compile examples with Weblogic 7.0 SP4

    Hi,
    i want to test the Toplink Examples with Weblogic but i get compilation errors all over. Can somebody help me out ?
    I use the Bea JDK 1.3.1_08 with a Weblogic 7.0 SP 4 Server. Here is the output of the compilation :
    [jar] Building jar: C:\PVCS\Dimensions\ORANT\Devtools\toplink\examples\wls
    70\examples\ejb\cmp20\singlebean\std_ejb20_cmp_account.jar
    [java] C:\PVCS\Dimensions\ORANT\Devtools\toplink\examples\wls70\examples\ej
    b\cmp20\singlebean\ejbcgen\examples\ejb\cmp20\singlebean\AccountBean_8259n1__Top
    Link_CMP_2_0.java:16: examples.ejb.cmp20.singlebean.AccountBean_8259n1__TopLink_
    CMP_2_0 should be declared abstract; it does not define __WL_getIsLocal() in exa
    mples.ejb.cmp20.singlebean.AccountBean_8259n1__TopLink_CMP_2_0
    [java] public class AccountBean_8259n1__TopLink_CMP_2_0 extends examples.ej
    b.cmp20.singlebean.AccountBean implements Cloneable, TopLinkCmpEntity, WLEnterpr
    iseBean {
    [java] ^
    [java] 1 error
    [java] Exec failed .. exiting
    BUILD FAILED
    The jar files of the examples don't deploy either on the server.
    thx,
    Daniel

    TopLink does not have anything specific to a particular JDBC driver or version built into the JAR.
    TopLink 9.0.3 ships with a version of HSQL and places that version's JAR file on its classpath. If you wish to use another version you will need to edit the workbench.cmd or workbench.sh script to replace the existing HSQL JAR file with the one from the version you wish to use.
    The entry that references the HSQL jar is "%TL_HOME%\HSQL\lib\hsqldb.jar".
    Doug

  • Webdynpro ABAP & JAVA step by step example with screen shots

    hi experts,
    i am new in webdynpro. i want to learn webdynpro so any one plz help me how to create,how to install,connect,and how to execute plz send any documents for webdynpro ABAP & JAVA step by step examples with screen shots.it's really helpful for my carrier.
    thanks and regards,
    sapbbm.

    hi bala,
      check out this URL you have 41 sample codes and PDF of Webdynpro for JAVA.
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/49f2ea90-0201-0010-ce8e-de18b94aee2d
    Thanks
    Gopi

  • Help. Going crazy with subclass.

    I am extending class Client with myClient. Why do I get a symbol not found in the myClient() constructor?
    // File: Client.java
    package testproj;
    public class Client {
        public Client(String conn){
            String xyz=conn;
    // File: myClient.java
    package testproj;
    public class myClient extends Client {
    // Gives error on the myClient Constructor as follows:
    // C:\App\testproj\src\testproj\myClient.java:5: cannot find symbol
    // symbol  : constructor Client() location: class testproj.Client
        public myClient(String conn){  
            int x=1;
    }

    Typically when you extend a class it is because you do want to initialize, and probably use, what is in that class. This rings doubly true when you created the parent class specifically for extending it in this project.
    For example, why on earth would you override foo with the exact same method? I realize both are empty and you probably intend there to be different code in each, but as it currently stands, there is no reason to override foo, the foo in MyClient is just simply not needed.
    But in my opinion your real problem here is you haven't figured out what constructors and methods are for. Constructors are for initializing a class, methods are for java code. Your example falls into some wierd gray area the myVar=xyz definitely fits and belongs in the constructor, but adding the additional text should probably be handled by a method since it appears that getting the different strings presumably for output is the crux of what you are trying to do.
    The reason you don't want to initialize is because you think " take care" will somehow get added in if you run it the way you have it, which is exactly why this sort of stuff should not be in constructors. But rest assured, for as you have it, the string will not contain "Loser take care" because as soon as you set it to that you turn around and reset it to "Loser terminate his a**". Any other concerns you have about initialization the parent are equally unfounded in the code you provided.
    Plus you don't seem to be aware that there can be more than one constructor. If you just added the following to class Client just above your current constructor;
    public Client(){
    } then you can remove the (xyz) in your super call and not have to worry about anything.
    JSG

  • How do u get help from apple support with iChat? I was able to chat with support last week to solve my problem but now the same issue is back and I don't see the option to chat now?

    qHow do u get help from apple support with iChat? I was able to chat with support last week to solve my problem but now the same issue is back and I don't see the option to chat now?

    For what it is worth I have noticed a similar issue from the iPad3 while at work and home. At work we have two Apple TV 3rd Generation installed and tied to our A/V system. I believe the issue has to do with a timeout on the broadcast saying "here I am" and allowing devices to connect.
    For example:
    At work we have several Wi-Fi SSID being broadcast from Cisco APs. The only one we can use with the Apple TV is the one that uses a WEP since the others are either setup to be hidden, require web page authentication, or have a login requirement from employees. Essentially, what I believe the issue is that the Apple TV periodically broadcasts a message to other iOS devices that support Mirroring. When the Apple TV does not get a response from a device it goes into a dormant mode and requires either a command from the remote control or a reboot. This has been tested with both the power management enabled and not enabled with the same results.
    As for when I come home, the Apple TV3 has not seen the device in some time and therefore is not broadcasting it's location information. A simple click of the circle or menu keys on the remote will give it the command to start broadcasting again and allow the iPad3 to see the Apple TV. When trying to Home Share the computer can not play (iTunes 11, Win8RTM) until the Apple TV is awoken then it will show up for mirroing.
    This may or may not assist you but, it hopefully explains how the issue may be happening.

  • Error running A Simple MDB example with oc4j

    Hi All,
    I am new to OC4J, I am trying the example for MDB from OTN's site, A Simple MDB example with OC4J. When I start my OC4J on the command line > java -jar oc4j.jar
    I get the following exception:
    Error deploying file:/C:/unzipped/mdb_hello_world/build/mdb/mdb.jar homes: No lo
    cation set for Topic resource MessageDrivenBean MDB
    Error in application mdb: Error loading package at file:/C:/unzipped/mdb_hello_w
    orld/build/mdb/mdb.jar, Error deploying file:/C:/unzipped/mdb_hello_world/build/
    mdb/mdb.jar homes: No location set for Topic resource MessageDrivenBean MDB
    04/07/09 15:21:40 Error instantiating application 'mdb' at file:/C:/unzipped/mdb
    helloworld/build/mdb.ear: Error initializing ejb-module; Exception Error in ap
    plication mdb: Error loading package at file:/C:/unzipped/mdb_hello_world/build/
    mdb/mdb.jar, Error deploying file:/C:/unzipped/mdb_hello_world/build/mdb/mdb.jar
    homes: No location set for Topic resource MessageDrivenBean MDB
    04/07/09 15:21:41 Error starting HTTP-Server: Address already in use: JVM_Bind
    04/07/09 15:21:41 Oracle Application Server Containers for J2EE 10g (9.0.4.0.0)
    initialized
    I have just followed all the steps provided to run the example exactly as given.
    I did add my Topic and TopicConnectionFatory entries in my jms.xml -
    <topic name="The Topic" location="jms/theTopic">
    <description>A MDB topic</description>
    </topic>
    <topic-connection-factory location="jms/theTopicConnectionFactory" />
    Here is the ejb-jar.xml given in the example:
    <?xml version="1.0"?>
    <!DOCTYPE ejb-jar>
    <ejb-jar>
    <enterprise-beans>
    <message-driven>
    <description>My message driven bean</description>
    <ejb-name>MDB</ejb-name>
    <ejb-class>MDB</ejb-class>
    <transaction-type>Container</transaction-type>
    <message-driven-destination>
    <destination-type>javax.jms.Topic</destination-type>
    <subscription-durability>NonDurable</subscription-durability>
    </message-driven-destination>
    <resource-ref>
    <description>The log topic where log events are broadcasted...</description>
    <res-ref-name>jms/theTopic</res-ref-name>
    <res-type>javax.jms.Topic</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    <resource-ref>
    <description>The Factory used to produce connections to the log topic...</description>
    <res-ref-name>jms/theTopicConnectionFactory</res-ref-name>
    <res-type>javax.jms.TopicConnectionFactory</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </message-driven>
    </enterprise-beans>
    <assembly-descriptor>
    <container-transaction>
    <method>
    <ejb-name>MDB</ejb-name>
    <method-name>*</method-name>
    </method>
    <trans-attribute>Supports</trans-attribute>
    </container-transaction>
    </assembly-descriptor>
    </ejb-jar>
    Here is my orion-ejb-jar.xml:
    <?xml version="1.0"?>
    <!DOCTYPE orion-ejb-jar PUBLIC "-//Evermind//DTD Enterprise JavaBeans 1.1 runtime//EN" "http://xmlns.oracle.com/ias/dtds/orion-ejb-jar.dtd">
    <orion-ejb-jar deployment-version="1.0.2.2" deployment-time="e7f5a3f42d">
    <enterprise-beans>
    <message-driven-deployment name="MDB" destination-location="jms/theTopic" connection-factory-location="jms/theTopicConnectionFactory">
    <resource-ref-mapping name="jms/theTopic" />
    <resource-ref-mapping name="jms/theTopicConnectionFactory" />
    </message-driven-deployment>
    </enterprise-beans>
    <assembly-descriptor>
    <default-method-access>
    <security-role-mapping name="&lt;default-ejb-caller-role&gt;" impliesAll="true" />
    </default-method-access>
    </assembly-descriptor>
    </orion-ejb-jar>
    I don't know what is wrong. Please help me.
    Rohini

    Hello,
    I guess that you didn't define the Topic and/or TopicConnectionFactory on your OC4J
    Inside $J2EE_HOME/config (see: subfolders .../j2ee/home/config e.g.)folder are several xml files appropriate for OC4J configuration. There's also jms.xml. Please, verify this one, it should have some entries for your settings.
    Just like in an example below:
    <topic-connection-factory name="TopicConnectionFactory" location="jms/TopicConnectionFactory"/>
    <topic name="theTopic" location="jms/theTopic"/>
    The names should be the same like in your MDB deployment descriptors. It works of course after next OC4J server restart.
    I hope helped you
    Krzysztof

  • Building J2EE examples with Ant 1.3 on WinXP

    I just installed J2EE 1.3.1 and set all environment variables according to J2EE/Ant documentation. I am trying to build the examples with Ant 1.3 and just before it tries to compile the first example, I get a "NTVDM.EXE Error while setting up environment" error window. This occurs every time I try this examples build. After I close this error window, the compiles fail mostly because the javax.ejb package classes cannot be found.
    Have I overlooked something here? Can anyone shed some insight on this problem?
    -Ryan

    Didn't think I'd be replying to so many of my own messages :-) ..., but anyway the problem with the NTVDM.EXE error message does not go away. I found that it's happens when Ant reads the system environment in the "property" task in build.xml under examples directory:
    <property environment="myenv" />
    <!--
    references to ${myenv.J2EE_HOME} and so on
    -->
    So I replaced occurences of ${myenv.<J2EE_HOME>} with the literal value, in my case, "C:\j2sdkee1.3.1" and now it works. Hope this helps.
    Cheers,
    Lakshmi.

  • How do i extend my network with a airport express

    How do I extend my network with mt airport express

    Hi Tesserax, I'd like to join this discussion. It seems Jasonbeyer didn't reply, but I have a question related to his.
    I'd like to extend the wireless signal from my Cisco Model DPC/EPC2202 VoIP Cable Modem (802.11n) to the living room where, at the moment, it is non-existent. I assume there's inteference or the signal cannot reach through the concrete walls and rooms leading up from my bedroom to the living room.
    My question is:
    I'm thinking of extending my wi-fi signal by using the Airport Express and simultaneously using it to connect to my hi-fi to play iTunes from my bedroom's iMac.
    Something's telling me it's not going to be that easy. I'm using an iMac (7,1) if that's any help or clue.
    What are the things I should take note of and will Airport Express be compatible with my modem? Would I have to get TWO Aiport Express to bridge the signal to my living room?
    Thank you everyone for your time. Cheers!
    Kane

  • How I extend my wifi with a Vodafone router?

    Hello, I have a DSL connection via Vodafone wifi Router (DSL-Easybox A 601 WLAN), and I would like to extend this wifi with my AEBS, but when I try to configurate it via wifi to to this "bridge", at the moment I select my current wifi, a message appears "the wifi you selected can not be extended", so how can I do it?
    I simply can not change the vodaphone router for this AEBS, because I would loose the phone, and the range od this vodafone router is limited, can you please help me?
    To do it via cable is not an option as well.
    Thanks,
    Clayton

    If you check your Vodafone router, you should see an available LAN <-> port on the back. Connect an ethernet cable from this port to the port on an ethernet powerline adapter and plug it into a nearby AC socket.
    At the location of the AEBS, plug the other powerline adapter into a nearby AC socket and connect an ethernet cable from the adapter to the WAN (circle icon) port on the AEBS.
    If you need more info on ethernet powerline adapters, you can enter this phrase in the search engine of your browser.
    Push the reset button on the AEBS until you see the amber light blink more quickly and continue holding a few more seconds after this and release
    Open Macintosh HD > Applications > Utilities > AirPort Utility
    Click Manual Setup
    Click the Base Station tab just below the row of icons
    Assign a name to your AEBS, device password, and adjust Time Zone settings
    Click the Wireless tab just below the row of icons
    Wireless Mode = Create a wireless network
    Wireless Network Name = Exact name of your Vodafone wireless network
    Radio Mode = 802.11n (802.11b/g compatible) or similar
    Channel = Automatic
    Wireless Security = Exact same security that your Vodafone router is using. You may need to consult the product documentation or Vodafone support to obtain this information
    Wireless Password = Same password as your Vodafone wireless network
    Click the Internet icon
    Connect Using = Ethernet
    Connection Sharing = Off (Bridge Mode)
    Update to save changes

  • Extending SOA domain with OSB classpath problem

    Trying to extend SOA 11.1.1.3 domain with OSB but getting classpath errors on start-up of admin server. I can see that class com.bea.wli.timer.JndiAccess is in modules/com.bea.alsb.timer_1.2.0.0.jar but I have no idea how to get the domain wizard to add this to the classpath? It doesn't appear as a library in the 'Manage Deployments' screen
    <01-Jul-2010 16:28:25 o'clock BST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'ALSB Framework Starter Application' due to error weblogic.management.DeploymentException: .
    weblogic.management.DeploymentException:
    at weblogic.application.internal.BaseDeployment.throwAppException(BaseDeployment.java:157)
    at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:371)
    at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:58)
    at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
    Truncated. see log file for complete stacktrace
    Caused By: java.lang.ClassNotFoundException: com.bea.wli.timer.JndiAccess
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    Truncated. see log file for complete stacktrace
    >
    <01-Jul-2010 16:28:30 o'clock BST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'XBus Kernel' due to error weblogic.management.DeploymentException: .
    weblogic.management.DeploymentException:
    at weblogic.application.internal.BaseDeployment.throwAppException(BaseDeployment.java:157)
    at weblogic.application.internal.BaseDeployment.prepare(BaseDeployment.java:371)
    at weblogic.application.internal.EarDeployment.prepare(EarDeployment.java:58)
    at weblogic.application.internal.DeploymentStateChecker.prepare(DeploymentStateChecker.java:154)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.prepare(AppContainerInvoker.java:60)
    Truncated. see log file for complete stacktrace
    Caused By: java.lang.ClassNotFoundException: com.bea.wli.config.spi.ConfigUpgrader
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:280)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoad
              r.java:253)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:177)
    Truncated. see log file for complete stacktrace
    >
    <01-Jul-2010 16:28:31 o'clock BST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'ALSB UDDI Manager' due to error java.lang.NullPointerException.
    java.lang.NullPointerException
    at com.bea.wli.sb.uddi.init.UDDIAppListener$2.run(UDDIAppListener.java:107)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:147)
    at weblogic.security.Security.runAs(Security.java:61)
    at com.bea.wli.sb.uddi.init.UDDIAppListener.preStart(UDDIAppListener.java:102)
    Truncated. see log file for complete stacktrace
    Caused By: java.lang.NullPointerException
    at com.bea.wli.sb.uddi.init.UDDIAppListener$2.run(UDDIAppListener.java:107)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:147)
    at weblogic.security.Security.runAs(Security.java:61)
    at com.bea.wli.sb.uddi.init.UDDIAppListener.preStart(UDDIAppListener.java:102)
    Truncated. see log file for complete stacktrace
    >
    <01-Jul-2010 16:28:38 o'clock BST> <Error> <Deployer> <BEA-149205> <Failed to initialize the application 'EJB Transport Provider' due to error java.lang.ClassNotFoundException: com.bea.wli.config.derivedcache.DerivedTypeDef.
    java.lang.ClassNotFoundException: com.bea.wli.config.derivedcache.DerivedTypeDef
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:280)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:253)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:177)
    Truncated. see log file for complete stacktrace
    Caused By: java.lang.ClassNotFoundException: com.bea.wli.config.derivedcache.DerivedTypeDef
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:280)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:253)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:177)
    Truncated. see log file for complete stacktrace

    Thanks for the response mr. Taylor.
    As I said, I extended my domain with single server topology and noticed that none of the osb modules were deployed on weblogic. So, although the domain is extended now It seems as if nothing happened since none of the osb features are working. This includes its console http://host:port/sbconsole which does not work, and also enterprise manager /em . I think there is something strange because when I tried to create a new domain, instead of extending, everything worked normal: Lots of OSB modules deployed on Weblogic and the /sbconsole and /em consoles working just fine. But I simple can't recreate the domain because of the multitude of configurations that would need to be redone.
    Any help will be appretiated !
    Thanks

  • Shopping cart with JSC

    Hi,
    I wanna make a shopping cart, I dont know how to make with JSC, If ani1 has got code for shopping cart or ani instruction, resources, I'll be really glad if ani1 help me.
    Waiting for kind reply.
    Thanx.

    Hi Gaurav,
    Thanks for your response, but we have standlone scenario( No ECC), we have the Service Hierarchy, Category and Product all setup for Service, yet the system is not creating the SC with Service Item via PR Data Coming in to SRM System.
    Also, we tried the same directly from SRM system using describe what you need, and their as well the SC goes with Service category but when SC details are shown up it shows as Outline Item, where again we need to add subline using service category. Ideally i suppose it should take the Service Category which we added at the time of filling details in Describe what you need.
    Please suggest, where in my main concern was in standalone SRM system if we have material PR data, then apart from the Category to be used Service is their any other parameter to be passed in, to create SC with Service Item.
    Regards,
    Gaurav

  • Help need in keylistener with image

    Hi experts,
    How to add the keylistener to a scrollpane for an image update or add image to the scrollpane. The solution will not using swing. Please send an example with a source code.
    Thanks in advance.

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import java.net.*;
    public class KeyTest4 extends Applet
        public void init()
            ImageEditorPanel editorPanel = new ImageEditorPanel();
            ScrollPane scrollPane = new ScrollPane();
            scrollPane.add(editorPanel);
            setLayout(new BorderLayout());
            add(new GridPanel(editorPanel), "North");
            add(scrollPane);
        public static void main(String[] args)
            Applet applet = new KeyTest4();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            applet.start();
            f.setVisible(true);
    class ImageEditorPanel extends Panel
        ImageLoader imageLoader;
        List imageList;
        int rows, cols;
        Choice rowChoice;
        boolean showGrid;
        Color gridColor;
        int gridSize;
        int dx, dy;
        Point cursor;
        public ImageEditorPanel()
            imageLoader = new ImageLoader(this);
            imageList = new ArrayList();
            rows = 1;
            cols = 3;
            showGrid = true;
            gridColor = new Color(200,240,240);
            gridSize = 100;
            addKeyListener(new KeyNavigator(this));
            dx = dy = 10;
            cursor = new Point(10,10);
        public void paint(Graphics g)
            super.paint(g);
            int w = getWidth();
            int h = getHeight();
            if(showGrid)
                g.setColor(gridColor);
                int xInc = (w - cols * gridSize)/cols + gridSize;
                int yInc = (h - rows * gridSize)/rows + gridSize;
                int x1 = xInc, y1 = 0, x2, y2 = h;
                for(int j = 0; j < cols - 1; j++)
                    g.drawLine(x1, y1, x1, y2);
                    x1 += xInc;
                x1 = 0; y1 = yInc; x2 = w;
                for(int j = 0; j < rows - 1; j++)
                    g.drawLine(x1, y1, x2, y1);
                    y1 += yInc;
            // render images
            ImageLocator locator;
            Image image;
            Point p;
            int x, y;
            int xInc = w / cols;
            int yInc = h / rows;
            for(int j = 0; j < imageList.size(); j++)
                locator = (ImageLocator)imageList.get(j);
                image = locator.getImage();
                p = locator.getCell();
                x = p.y * xInc - xInc/2 - image.getWidth(this)/2;
                y = p.x * yInc - yInc/2 - image.getHeight(this)/2;
                g.drawImage(image, x, y, this);
            // render cursor
            g.setColor(new Color(240,200,200));
            int cx = cursor.x;
            int cy = cursor.y;
            g.fillOval(cx - 10, cy - 10, 20, 20);
            g.setColor(new Color(140,200,100));
            g.drawLine(cx, cy - 12, cx, cy - 16);
            g.drawLine(cx - 12, cy, cx - 16, cy);
            g.drawLine(cx, cy + 12, cx, cy + 16);
            g.drawLine(cx + 12, cy, cx + 16, cy);
        public Dimension getPreferredSize()
            Dimension d = new Dimension(400,400);
            ScrollPane sp = getScrollPane(this);
            Insets insets = sp.getInsets();
            int hInsets = insets.left + insets.right;
            int vInsets = insets.top + insets.bottom;
            if(sp != null)
                d = sp.getViewportSize();
            if(d.width - hInsets < cols * gridSize)
                d.width = cols * gridSize;
            if(d.height - vInsets < rows * gridSize)
                d.height = rows * gridSize;
            return d;
        public void addImage()
            Point p = getCell();
            Graphics g = getGraphics().create();
            g.setColor(Color.red);
            Image image = imageLoader.getImage();
            imageList.add(new ImageLocator(image, p));
            resetGrid();
        public void removeImage()
            Point cell = getCell();
            ImageLocator locator;
            for(int j = 0; j < imageList.size(); j++)
                locator = (ImageLocator)imageList.get(j);
                Point p = locator.getCell();
                if(cell.equals(p))
                    imageList.remove(j);
                    break;
            resetGrid();
        private Point getCell()
            Point p = new Point();
            int w = getWidth();
            int h = getHeight();
            int xInc = w / cols;
            int yInc = h / rows;
            p.x = 1 + cursor.y / yInc;  // row
            p.y = 1 + cursor.x / xInc;  // col
            return p;
        private void resetGrid()
            int oldGridSize = gridSize;
            int maxWidth = 0;
            int maxHeight = 0;
            ImageLocator locator;
            Image image;
            int w, h;
            for(int j = 0; j < imageList.size(); j++)
                locator = (ImageLocator)imageList.get(j);
                image = locator.getImage();
                w = image.getWidth(this);
                h = image.getHeight(this);
                if(w > maxWidth)
                    maxWidth = w;
                if(h > maxHeight)
                    maxHeight = h;
            if(maxWidth != gridSize || maxHeight != gridSize)
                gridSize = Math.max(maxWidth, maxHeight);
            if(maxWidth == 0 && maxHeight == 0)
                gridSize = 100;
            if(gridSize != oldGridSize)
                validateScrollPane();
            else
                repaint();
        private ScrollPane getScrollPane(Component c)
            while((c = c.getParent()) != null)
                if(c instanceof ScrollPane)
                    return (ScrollPane)c;
            return null;
        public void addRow()
            rows++;
            rowChoice.add(String.valueOf(rows));
            rowChoice.select(rowChoice.getSelectedIndex() + 1);
            validateScrollPane();
        public void setShowGrid(boolean isVisible)
            showGrid = isVisible;
            repaint();
        public void setCursor(int x, int y)
            cursor.translate(x * dx, y * dy);
            if(!isInBounds())
                scrollToView();
            repaint(cursor.x - 28, cursor.y - 28, 56, 56);
        public void centerCursor()
            ScrollPane sp = getScrollPane(this);
            if(sp == null)
                return;
            Point p = sp.getScrollPosition();
            Dimension d = sp.getViewportSize();
            cursor.x = p.x + d.width/2;
            cursor.y = p.y + d.height/2;
            repaint();
        private boolean isInBounds()
            ScrollPane sp = getScrollPane(this);
            if(sp == null)
                return true;
            Point p = sp.getScrollPosition();
            Dimension viewSize = sp.getViewportSize();
            if(cursor.x + 16 > p.x - viewSize.width ||
               cursor.x - 16 < p.x || cursor.y - 16 < p.y ||
               cursor.y + 16 > p.y - viewSize.height)
                return false;
            return true;
        private void scrollToView()
            ScrollPane sp = getScrollPane(this);
            Point p = sp.getScrollPosition();
            Dimension viewSize = sp.getViewportSize();
            int x = p.x, y = p.y;
            if(cursor.x + 16 > p.x + viewSize.width)
                x = cursor.x + 16 - viewSize.width;
            if(cursor.x - 16 < p.x)
                x = cursor.x - 16;
            if(cursor.y + 16 > p.y + viewSize.height)
                y = cursor.y + 16 - viewSize.height;
            if(cursor.y - 16 < p.y)
                y = cursor.y - 16;
            sp.setScrollPosition(x,y);
        public void setRows(int rows)
            this.rows = rows;
            validateScrollPane();
        public void setCols(int columns)
            cols = columns;
            validateScrollPane();
        private void validateScrollPane()
            ScrollPane sp = getScrollPane(this);
            if(sp == null)
                return;
            invalidate();
            repaint();
            sp.validate();
        public void setReference(Choice choice)
            rowChoice = choice;
    class GridPanel extends Panel
        ImageEditorPanel imagePanel;
        public GridPanel(ImageEditorPanel iep)
            imagePanel = iep;
            final Checkbox marker = new Checkbox("mark", true);
            marker.addItemListener(new ItemListener()
                public void itemStateChanged(ItemEvent e)
                        imagePanel.setShowGrid(marker.getState());
            final Choice
                rowChoice = new Choice(),
                colChoice = new Choice();
            rowChoice.add("1");
            for(int j = 0; j < 4; j++)
                colChoice.add(String.valueOf(j + 1));
            colChoice.select(2);
            ItemListener l = new ItemListener()
                public void itemStateChanged(ItemEvent e)
                    if(e.getStateChange() == ItemEvent.SELECTED)
                        Choice choice = (Choice)e.getSource();
                        int value = choice.getSelectedIndex() + 1;
                        if(choice == rowChoice)
                            imagePanel.setRows(value);
                        if(choice == colChoice)
                            imagePanel.setCols(value);
            rowChoice.addItemListener(l);
            colChoice.addItemListener(l);
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            add(marker, gbc);
            gbc.anchor = gbc.EAST;
            add(new Label("rows"), gbc);
            gbc.anchor = gbc.WEST;
            add(rowChoice, gbc);
            gbc.anchor = gbc.EAST;
            add(new Label("cols"), gbc);
            gbc.anchor = gbc.WEST;
            add(colChoice, gbc);
            imagePanel.setReference(rowChoice);
    class ImageLocator
        Image image;
        Point cell;
        public ImageLocator(Image image, Point p)
            this.image = image;
            cell = p;
        public Image getImage()
            return image;
        public Point getCell()
            return cell;
    class ImageLoader
        Image[] images;
        int index;
        public ImageLoader(Component c)
            loadImages(c);
            index = 0;
        public Image getImage()
            return images[index++ % images.length];
        private void loadImages(Component c)
            String prefix = "images/";
            String ext = ".jpg";
            String[] fileNames = {
                "greathornedowl", "owls", "bclynx", "coyote"
            images = new Image[fileNames.length];
            MediaTracker tracker = new MediaTracker(c);
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            int id = 0;
            for(int j = 0; j < images.length; j++)
                URL url = getClass().getResource(prefix + fileNames[j] + ext);
                images[j] = toolkit.getImage(url);
                tracker.addImage(images[j], id++);
            try
                tracker.waitForAll();
            catch(InterruptedException ie)
                System.out.println("interrupted: " + ie.getMessage());
    class KeyNavigator extends KeyAdapter
        ImageEditorPanel imagePanel;
        final static int
            UP     = KeyEvent.VK_UP,
            LEFT   = KeyEvent.VK_LEFT,
            DOWN   = KeyEvent.VK_DOWN,
            RIGHT  = KeyEvent.VK_RIGHT,
            ADD    = KeyEvent.VK_A,
            REMOVE = KeyEvent.VK_R,
            CENTER = KeyEvent.VK_C,
            ENTER  = KeyEvent.VK_ENTER;
        public KeyNavigator(ImageEditorPanel iep)
            imagePanel = iep;
        public void keyPressed(KeyEvent e)
            int keyCode = e.getKeyCode();
            int x = 0, y = 0;
            switch(keyCode)
                case UP:
                    y = -1;
                    break;
                case LEFT:
                    x = -1;
                    break;
                case DOWN:
                    y = 1;
                    break;
                case RIGHT:
                    x = 1;
                    break;
                case ADD:
                    imagePanel.addImage();
                    return;
                case REMOVE:
                    imagePanel.removeImage();
                    return;
                case CENTER:
                    imagePanel.centerCursor();
                    return;
                case ENTER:
                    imagePanel.addRow();
                    return;
                default:
                    return;
            imagePanel.setCursor(x, y);
    }

Maybe you are looking for