Dynamic Class Downloading and EJBs

Hi all,
I have one session EJB with business method getObject returning a serializable object which class implements MyObject interface.
This object's class, named MyObjectImpl, is in only deployed on server within my EAR file.
I would like my client classpath not containing MyObjectImpl class but only MyObject class (the implemented interface).
Could you suggest a way to do this, by dynamically downloading implementation class at runtime so I can correcly get casting?
Thanks in advance
Fil

Hi Fil,
There's no portable way to accomplish this in the Java EE plaform. Java EE requires that all dependent classes needed by a component be packaged with that component at deployment time. Applications are not permitted to dynamically load classes, as this would be both a security issue and a correctness issue. This is true even for clent components, which is why the Java EE platform has a first-class client component called an Application Client. You can find out more about the difference between an Application Client and a stand-alone client in our EJB FAQ.
https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html
--ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Dynamic Class Downloading difficulty

    Hi RMI Specialists,
    I am experiencing a possible dynamic class loading issue when attempting to separate the client & server codes across 2 separate Windows (XP & 2000) systems. This exercise (from ch13 of Oreilly�s Learning Java) is made up
    of the following interfaces and classes:
    On the Server side:
    package LearningJavaServer;
    import java.rmi.*;
    import java.util.*;
    public interface RemoteServer extends Remote {
        Date getDate(  ) throws RemoteException;
        Object execute( WorkRequest work ) throws RemoteException;
    package LearningJavaServer;
    import java.rmi.*;
    import java.util.*;
    public class MyServer extends java.rmi.server.UnicastRemoteObject
        implements RemoteServer {
        public MyServer(  ) throws RemoteException { }
        // implement the RemoteServer interface
        public Date getDate(  ) throws RemoteException {
            return new Date(  );
        public Object execute( WorkRequest work ) throws RemoteException {
            return work.execute(  );
        public static void main(String args[]) {
            try {
                RemoteServer server = new MyServer(  );
                Naming.rebind("NiftyServer", server);
            } catch (java.io.IOException e) {
                // problem registering server
    package LearningJavaServer;
    import java.io.*;
    public class Request implements java.io.Serializable {}
    package LearningJavaServer;
    public abstract class WorkRequest extends Request {
        public abstract Object execute(  );
    }On the Client side:
    package LearningJavaClient;
    import java.rmi.*;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    public class MyClient {
        public static void main(String [] args)
          throws RemoteException {
            new MyClient( args[0] );
        public MyClient(String host) {
            try {
                RemoteServer server = (RemoteServer)
                    Naming.lookup("rmi://"+host+"/NiftyServer");
                System.out.println( server.getDate(  ) );
                System.out.println(
                  server.execute( new MyCalculation(2) ) );
            } catch (java.io.IOException e) {
                  // I/O Error or bad URL
                     System.out.println( e );
            } catch (NotBoundException e) {
                  // NiftyServer isn't registered
               System.out.println( e );
    package LearningJavaClient;
    import java.rmi.*;
    import java.util.*;
    public interface RemoteServer extends Remote {
        Date getDate(  ) throws RemoteException;
        Object execute( WorkRequest work ) throws RemoteException;
    package LearningJavaClient;
    public class MyCalculation extends WorkRequest {
        int n;
        public MyCalculation( int n ) {
            this.n = n;
        public Object execute(  ) {
            return new Integer( n * n );
    package LearningJavaClient;
    import java.io.*;
    public class Request implements java.io.Serializable {}
    package LearningJavaClient;
    public abstract class WorkRequest extends Request {
        public abstract Object execute(  );
    }Steps to invoke all services on the server side:
    cd C:\Documents and Settings\htran\JavaRMI\build\classes on both systems;
    ( i ) start rmiregistry.
    ( ii ) java -Djava.rmi.server.codebase='http://serverhostname/LearningJavaServer/' -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaServer.MyServer
    Steps to invoke all services on the client side:
    ( i ) java -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    java.rmi.NotBoundException: NiftyServer
    Or
    ( ii ) java -Djava.rmi.server.codebase='http://clienthostname/LearningJavaClient/' -Djava.security.policy="C:\Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    java.rmi.UnmarshalException: Error unmarshaling return; nested exception is:
    java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJavaClient/'
    Is it possible that this issue could have been caused by either the Request/WorkRequest classes which are present on both system? Likewise, is the location of invoking RMI registry on the server correct?
    Both systems have got their own web servers (http://serverhostname/LearningJavaServer & http://clienthostname/LearningJavaClient).
    No firewalls between the two systems and the security files (C:\Document Settings\htran\.java.policy) are made up of the following 2 lines:
        grant codeBase "file:/home/jones/src/" {
            permission java.security.AllPermission;
        };Another issue that I am having is that the server process below is that it keeps on dropping off after a minute or two:
    C:\Documents and Settings\htran\JavaRMI\build\classes>java -Djava.rmi.se
    rver.codebase='http://clienthostname/LearningJavaClient/' -Djava.security.policy="C:\
    Documents and Settings\htran\.java.policy" -cp . LearningJavaClient.MyClient serverhostname
    This exercise has worked fine when running all the codes on the same host.
    I am running Netbeans 5.5, JDK1.5.0_11 on Windows 2000 (Server) & XP (Client).
    Any assistance would be appreciated.
    Many thanks,
    Henry

    Hi Esmond,
    You still have an empty catch block for the IOException. Fix that first. I >can't possibly tell what's going on until you can at least bind the >service.OK. MyServer.java below no longer throws RemoteExceptions in both of its methods and added the print stacktrace to catch the empty IOException earlier.
    public class MyServer extends java.rmi.server.UnicastRemoteObject
        implements RemoteServer {
        public MyServer(  ) throws RemoteException { }
        public Date getDate(  ) {
            return new Date(  );
        public Object execute( WorkRequest work ) {
            return work.execute(  );
        public static void main(String args[]) {
            System.setSecurityManager(new RMISecurityManager());
            try {
                RemoteServer server = new MyServer(  );
                Naming.rebind("NiftyServer", server);
            } catch (java.io.IOException e) {
                // problem registering server
               System.out.println("IOexception from MyServer");
                e.printStackTrace();
            } catch (Exception e) {
                System.out.println("General Exception from MyServer");
                e.printStackTrace();
    }The following error messages were produced when launching MyServer.class. I have broken it into 2 separate attempts. One with Dynamic Class Downloading & one without.
    Use CodeBase when launches MyServer.
    C:\Documents and Settings\abc\JavaRMI\build\classes>java -Djava.rmi.server.codebase='http://clienthostname/LearningJava/' -Djava.security.policy="C:\Documents and
    Settings\abc\.java.policy" -cp . LearningJava.MyServer
    IOexception from MyServer
    java.rmi.UnmarshalException: Error unmarshaling return; nested exception is: java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJava/'
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Unknown Source)
    at LearningJava.MyServer.main(MyServer.java:28)
    Caused by: java.net.MalformedURLException: no protocol: 'http://clienthostname/LearningJava/'
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at java.net.URL.<init>(Unknown Source)
    at sun.rmi.server.LoaderHandler.pathToURLs(Unknown Source)
    at sun.rmi.server.LoaderHandler.getDefaultCodebaseURLs(Unknown Source)
    at sun.rmi.server.LoaderHandler.loadClass(Unknown Source)
    at java.rmi.server.RMIClassLoader$2.loadClass(Unknown Source)
    at java.rmi.server.RMIClassLoader.loadClass(Unknown Source)
    at sun.rmi.server.MarshalInputStream.resolveClass(Unknown Source)
    at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
    at java.io.ObjectInputStream.readClassDesc(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    ... 5 more
    Does NOT use CodeBase when launches MyServer
    C:\Documents and Settings\abc\JavaRMI\build\classes>java -Djava.security.policy="C:\Documents and Settings\abc\.java.policy" -cp . LearningJava.MyServer
    IOexception from MyServer
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:385)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240)
    at sun.rmi.transport.Transport$1.run(Transport.java:153)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:149)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
    at java.lang.Thread.run(Thread.java:595)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
    at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
    at sun.rmi.server.UnicastRef.invoke(Unknown Source)
    at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
    at java.rmi.Naming.rebind(Unknown Source)
    at LearningJava.MyServer.main(MyServer.java:28)
    Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
    at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:375
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240)
    at sun.rmi.transport.Transport$1.run(Transport.java:153)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:149)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
    at java.lang.Thread.run(Thread.java:595)
    Caused by: java.lang.ClassNotFoundException: LearningJava.RemoteServer
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:242)
    at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:707)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:651)
    at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:588)
    at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628)
    at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294
    at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238)
    at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1500)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1463)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1699)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
    ... 9 more
    I now understand that you do want to use dynamic class loading, and >moreover that you want to do it from the client to the server, in which >case you do need java.rmi.server.codebase at the client and you do >also need a codebase server. However the client and server can both >use the same codebase server, and indeed in this situation I don't >see why the server needs a codebase server or setting at all actually. I >don't really see why you want to use it from the client either, if this is a >closed system but that's your problem not mine.I now use only one codebase server. ie the one on the Client side where MyCalculation.class resides. You are right it is not necessary to use codebase when launching MyServer since the Client side does not need to download any additional classes over to the client side. Nevertheless, neither of the above startups (with/without) codebase worked even though the error messages were slightly different.
    Btw, can you explain what you mean by a "close system" compared to an "opened system"?
    java.net.MalformedURLException: no >protocol: 'http://clienthostname/LearningJava/'
    That doesn't make sense. Are you sure you're transcribing it correctly? >Also what line of code is throwing it?Here is the code for MyClient which explains that the line java.net.MalformedURLException: came from line 32, the printStackTrace() from IOException.
    public class MyClient {
        public static void main(String [] args)
          throws RemoteException {
          System.setSecurityManager(new RMISecurityManager());
            new MyClient( args[0] );
        public MyClient(String host) {
            try {
                RemoteServer server = (RemoteServer)
                    Naming.lookup("rmi://"+host+"/NiftyServer");
                System.out.println( server.getDate(  ) );
                System.out.println(
                server.execute( new MyCalculation(2) ) );    // line 28
            } catch (java.io.IOException e) {
                  // I/O Error or bad URL
                  System.out.println("IOException from MyClient");
               e.printStackTrace();
            }  catch (NotBoundException e) {
                  // NiftyServer isn't registered
                  System.out.println("NotBoundException from MyClient");
               e.printStackTrace();
            } catch (Exception e) {
                  System.out.println("General Exception from MyClient");
                  e.printStackTrace();
    }I wouldn't pay much attention to this message since the MyServer has difficulty registering itself to RMI registry. As a result, MyClient could not
    locate MyServer via RemoteServer interface before giving up altogether.
    Unfortunately, I have not being able to create an interface (e.g. >MyCalculation.class as an interface, MyCalculationImpl.class as the >actual implementation of MyCalculation) since WorkRequest is an >abstract class, which does not allow MyClient to instanciates >MyCalculation on line 28.
    I don't see why not. What error messages/exceptions are you getting?
    Are you referring to the execute() method on line 13 in >RemoteServer.classNo, I am referring to line 28 of MyClient.class above after the following failed attempts to create an interface for MyCalculation.java:
    public interface MyCalculation extends WorkRequest { // Got a syntax error: interface expected here in Netbeans.
    } Or
    public interface MyCalculation {}
    public class MyCalculation extends WorkRequest extends MyCalculation { ... # Obviously cannot extend more than one class.Any suggestion?
    No. I said the remote method implementation (i.e. in your xxxImpl >class) doesn't need to be declared to throw RemoteException. The >remote method definition in the remote interface certainly does. I have taken out the RemoteException from 2 methods in MyServer.java. ie implementation of the RemoteServer.java.
    In short, I have used only one codebase server but puzzled whether MyCalculation.class (have split it up into interface & implementation) will be passed over to the
    server side by referenced, value or Dynamic Class Downloading. I do not want it to use Dynamic Class Downloading to do this.
    Thanks,
    Henry

  • Dynamic Class Loading and Stubs

    How Dynamic Class Loading is used on Java RMI, since stubs are generated on clients using Reflection API?
    I was reading Dynamic code downloading using JavaTM RMI (http://java.sun.com/javase/6/docs/technotes/guides/rmi/codebase.html), it seems to be out of date.
    For example, "The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the Java RMI registry bound to a name."

    "Enhancements in J2SETM 5.0
    Dynamic Generation of Stub Classes
    This release adds support for the dynamic generation of stub classes at runtime, obviating the need to use the Java(tm) Remote Method Invocation (Java RMI) stub compiler, rmic, to pregenerate stub classes for remote objects. *Note that rmic must still be used to pregenerate stub classes for remote objects that need to support clients running on _earlier versions_.*
    When an application exports a remote object (using the constructors or static exportObject methods(1) of the classes java.rmi.server.UnicastRemoteObject or java.rmi.activation.Activatable) and a pregenerated stub class for the remote object's class cannot be loaded, the remote object's stub will be a java.lang.reflect.Proxy instance (whose class is dynamically generated) with a java.rmi.server.RemoteObjectInvocationHandler as its invocation handler.
    An existing application can be deployed to use dynamically generated stub classes unconditionally (that is, whether or not pregenerated stub classes exist) by setting the system property java.rmi.server.ignoreStubClasses to "true". If this property is set to "true", pregenerated stub classes are never used.
    Notes:
    * If a remote object has pre-5.0 clients, that remote object should use a stub class pregenerated with rmic or the client will get an ClassNotFoundException deserializing the remote object's stub. Pre-5.0 clients will not be able to load an instance of a dynamically generated stub class, because such a class contains an instance of RemoteObjectInvocationHandler, which was not available prior to this release.
    * Prior to the J2SE 5.0 release, exporting a remote object would throw a java.rmi.StubNotFoundException if the pregenerated stub class for the remote object's class could not be loaded. With the added support for dynamically generated stub classes, exporting a remote object that has no pregenerated stub class will silently succeed instead. A user deploying a server application to support pre-5.0 clients must still make sure to pregenerate stub classes for the server's remote object classes, even though missing stub classes are no longer reported at export time. Such errors will instead be reported to a pre-5.0 client when it deserializes a dynamically generated stub class.
    (1) The static method UnicastRemoteObject.exportObject(Remote) is declared to return java.rmi.server.RemoteStub and therefore cannot be used to export a remote object to use a dynamically generated stub class for its stub. An instance of a dynamically generated stub class is a java.lang.reflect.Proxy instance which is not assignable to RemoteStub."
    http://java.sun.com/j2se/1.5.0/docs/guide/rmi/relnotes.html

  • Dynamic class loading and Casting

    Hi guys,
    spent lots of time trying to figure out how to do one thing with no luck, hope anybody can help me here. Here is what I have:
    I need to create a new object, I have dynamic variable of what kind of an object I need:
    sObjectType = "Article";
    ItemObject oItem = Item.init(1000, 1);           
    oItem.ArticleObjectCall();                      // ERROR is here, method does not exist, ArticleObjectCall is method of the Article classItem is a static Class that inits objects
    public class Item {
         public static ItemObject init(String sObjectType) {
                  ItemObject oClass = Class.forName("com.type." + sObjectType).newInstance();
                  return oClass;
    }Below are the 2 classes Article and ItemObject
    Article
    package com.type;
    public class Article extends ItemObject {     
         public void ArticleObjectCall() {
              System.out.println("Article Hello");
    ItemObject
    public class ItemObject {
         public ItemObject() {          
    }

    Ajaxian wrote:
    This is a method INIT, I am dynamically including class com.type.Article , Article extends ItemObject, I am casting new instance of Article to (ItemObject) to return a proper type but later when I try to call oClass object which is I believe my Article class, I get an error. None of which answers my question, yet it does show that you are thoroughly confused...
    String x = "blub";
    Object y = x;
    System.out.println(y.length); // We both know y is a string, but the compiler does not. => ErrorThe compiler enforces the rules of a static type system, your question is quite explicitly about dynamism, which is not without reason the antonym to statics. If you load classes dynamically, you need to use reflection to invoke their methods.
    With kind regards
    Ben

  • Dynamic Class Loading and Unloading

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

    I am trying to create a system where the class name and method name is
    picked up from a meta-data database and executed.
    This was accompanied using Dynamic Class loading. I tried to extend this to
    support versioning of meta-data. Here depending on the version of meta-data
    different libraries can be loaded and different implementations of object
    with the same name can be executed. This does not seem to work with Forte
    3.0.
    When the second Library is loaded the method execution does not work.
    (Even though the unload flag on the LoadLibrary is set)
    If the application is stopped and restarted pointing to the second library
    there is no problem. In a running application a dynamically loaded library
    does not seem to unload and reload a new library for the same class names.
    Has anyone tried sometime similar, is there a workaround for this type of
    problem.
    - Vivek

  • Dynamic class cast and instanceof

    I am looking for a way to dynamically test an object for being of a specific class. The instanceof operator can only be used with literally named classes I understand. So you cannot have something like boolean checkClass( Object o, Class c ) {
       return o instanceof c;
    } Is there any way to do something like this by use of the reflection API? The point is that instanceof only works statically, the reference type being tested for being specified at compile time. The question is whether it can be done with a reference type being specified at run-time, ie dynamically.

    There is a collection of parameters of various types, which is passed to some client module.
    There should be a, say 'checkParam' method for the client, which checks for existence of a certain parameter by its name, and also specified which class the parameter should have. So it should be called like
    checkParam( params, "paramName", String.class )I wanted to avoid hard-coded types, but have the class specified as an argument to this method. I feel like there should be some way to accomplish that. What swingfreak intended may be a way.

  • Classes, Stateful EJBs and EJB Container

    Hi,
    We have several doubts about classes, servlets, and EJBs.
    We have been told that the instance of non-static classes from JSPs or servlets
    can be a problem if we have a big number of clients connecting to weblogic (or
    any other app server). Would it be a problem? Is it a better practice to instantiate
    those classes from EJBs?
    We have been told that EJBs are managed by the EJB container, and it uses a pool
    for serving them to clients, passivating and activating them. This would include
    the classes instantiated inside them. Is it true?
    If all our guesses are true, the better way to implement a search with pagination
    would be a stateful EJB, using handlers to save it in the client's session. But
    we've heard that stateful EJBs are really bad for server's perfomance. Is it true?
    We are using Weblogic 7.0. If so, what are they useful for???
    If they can be a problem, how to build that searching using stateless EJBs?
    Best regards,
    Ignacio Sanchez

    You're right, the concrete tag to use seems to be:
    <replication-type>InMemory</replication-type>
    Anyway, do you have any further explanation on Stateful's behaviour with many
    clients and pagination implementation?
    "Stanley Beamish" <[email protected]> wrote:
    >
    "Ignacio Sanchez" <[email protected]> wrote in message
    news:[email protected]...
    Thanks for your replies.
    Anyway, I still have some questions about stateful EJBs. In a clusteredenvironment,
    we've been told that stateful EJBs are only balanced before create()method. So,
    if we have already "created" the Remote interface, we're using it,and the
    server
    fails and must be balanced to another instance, what will happen? Willwe
    lost
    that Remote interface and data included in it?
    Not necessarily, you can enable replication, which means that your stateful
    EJB's state (values of i-vars) can be replicated across nodes in a cluster.
    Search through the WLS cluster documentation for details.
    SB
    And about your suggestion on pagination using stateless. Could youplease
    explain
    it in more detail? I haven't understood it well.
    Thank you very much for your attention.
    "Sri" <[email protected]> wrote:
    Hi,
    Look below for my coments.
    S
    "Ignacio Sanchez" <[email protected]> wrote:
    Hi,
    We have several doubts about classes, servlets, and EJBs.
    We have been told that the instance of non-static classes from JSPsor
    servlets
    can be a problem if we have a big number of clients connecting to
    weblogic
    (or
    any other app server). Would it be a problem? Is it a better practice
    to instantiate
    those classes from EJBs?It all boils down to your architecture. If you have a lot of clients
    connecting
    to web container then and if each client needs objects stored in session
    then
    you have to refactor your object distribution. But this could be avoided
    by separating
    static content from dynamic content (using proxies, load balancersetc),
    having
    more web containers etc. It's not necessary to instantiate these classes
    in EJBs
    always (then you are increasing your memory footprint). The generalguidelne
    is
    to do more heavy duty work as you go deeper into tiers hopefully handling
    less
    connections etc.
    We have been told that EJBs are managed by the EJB container, and
    it
    uses a pool
    for serving them to clients, passivating and activating them. Thiswould
    include
    the classes instantiated inside them. Is it true?
    True.
    If all our guesses are true, the better way to implement a search
    with
    pagination
    would be a stateful EJB, using handlers to save it in the client'ssession.
    But
    we've heard that stateful EJBs are really bad for server's perfomance.
    Is it true?
    We are using Weblogic 7.0. If so, what are they useful for???
    True if misused as stateful EJBs, just like HTTP sessions could bereplicated
    and could be activated/passivated.
    If they can be a problem, how to build that searching using stateless
    EJBs?
    You could cache searchs and pass identity and page numbers to theSLSB.
    Best regards,
    Ignacio Sanchez

  • Dynamic implementation download for return values from EJB

    I try the following exemplary scenario regarding dynamic implementation download. Let's say there is a statless EJB deployed (e.g. OrderHandler) with a method getSomeOrder() returning Order object; where Order is actually an interface extending java.io.Serializable. For Order there is implementation class OrderImpl. Within the getSomeOrder() the EJB creates a new OrderImpl, populates it and returns as interface. The client looks up OrderHandler and calls getSomeOrder() method. Then, on Order a dummy: String getName() method is called.
    Now, the problem is various behavior with implementation dynamic download. I receive different behavior from 2 clients (1st being launched from within LAN with the server, 2nd from outside server's LAN). When I put OrderImpl in clients' classpaths, obviously they both work the same. When I leave only Order interface (!!the very goal of the test - dynamic impl. download!!), only the 1st client still works. I measured times in milis, and it looks that the OrderImpl is really downloaded, as the first getSomeOrder() call lasts around 10 times as long as further calls.
    The 2nd client hangs a while on the getSomeOrder() call and then throws UnmarshallException, stating that it has failed to unmarshal the returned object, which basically means no implementation got downloaded.
    Can anyone help?

    You can try putting the Impl classes on a webserver.
    while starting the server set the property
    -Djava.rmi.server.codebase=http://mywebserver:8080
    While running the client if the impl classes are not available in the classpath, it would download it from the webserver

  • Is Dynamic Class Loading(RMI) Possible in EJB?

    In Java RMI,it allows dynamic class loading,that is when the stub and interface class files are modified by the server,the client side can download the updated stub and inteface classes.
    As the remote interface of EJB extends Javax.ejb.EJBObject which in turn extends java.rmi.remote.Also the Home interface of EJB extends
    javax.ejb.EJBHome which also extends java.rmi.remote.
    Therefore I wonder if EJB also supports dynamic class
    loading as RMI does.If yes,how to do so?Is it the responsibility of the Application Servers and transparent
    to client? If No,then is this a defect in EJB??
    Thank you very much in advance!!
    John

    This would be done by the container and is transparent to the client. Most app servers support "hot deploy" where you can deploy beans while the server is running. This requires dynamic class loading.

  • Difference between narrow() method usage and simple class cast for EJB

    Hi,
    I have a very simple question:
    what is the difference between PortableRemoteObject.narrow(fromObj,
    toClass) method usage and simple class cast for EJB.
    For example,
    1)
    EJBObject ejbObj;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)PortableRemoteObject.narrow(ejbObj,ABean.class);
    OR
    2)
    EJBObject bean;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)ejbObj;
    Which one is better?
    P.S. I'm working with WL 6.1 sp2
    Any help would be appreciated.
    Thanks in advance,
    Orly

    [email protected] (Orly) writes:
    Hi,
    I have a very simple question:
    what is the difference between PortableRemoteObject.narrow(fromObj,
    toClass) method usage and simple class cast for EJB.
    For example,
    1)
    EJBObject ejbObj;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)PortableRemoteObject.narrow(ejbObj,ABean.class);
    OR
    2)
    EJBObject bean;
    // somewhere in the code the home.create() called for bean ...
    ABean a = (ABean)ejbObj;
    Which one is better?(1) is mandated by the spec. It is required because CORBA systems may
    not have sufficient type information available to do a simple case.
    P.S. I'm working with WL 6.1 sp2 You should always use PRO.narrow()
    andy

  • Dynamic class loading problem using unknown JAR archive and directory names

    I read the following article, which enlightened me a lot:
    Ted Neward: Understanding Class.forName().
    However, it took me some while to understand that my problem is the other way around:
    I know the name of the class, I know the name of the method,
    but my program/JVM does not know where to load the classes from.
    Shortly, my problem is that the server engine that I am writing
    uses two different versions of the same library.
    So I am trying out the following solution:
    My program is named TestClassPathMain.java
    Assume the two libraries are named JAR1.jar and JAR2.jar
    and the class/instance method that should
    be exposed to TestClassPathMain.java by them is named
    TestClass1.testMethod().
    As long as I was depending on just one library,
    I put JAR1.jar in the classpath before starting java,
    and I was happy for a while.
    At the moment I got the need to use another version of
    TestClass1.testMethod() packaged in JAR2.jar,
    a call would always access JAR1.jar's
    TestClass1.testMethod().
    I then decided to remove JAR1.jar from the classpath,
    and programmatically define two separate ClassLoaders, one for use
    with JAR1.jar and the other for use with JAR2.jar.
    However, the problem is only partly solved.
    Please refer to the enclosed code for details.
    (The code in the JAR1.jar/JAR2.jar is extremely simple,
    it just tells (by hardcoding) the name of the jar it is packaged in
    and instantiates another class packaged in the same jar using
    the "new" operator and calls a method on it. I don't enclose it.)
    The TestClassPathMain.java/UC1.java/UC2.java code suite was
    successfully compiled with an arbitrary of JAR1 or JAR2 in the classpath,
    however removed from the classpath at runtime.
    (I know that this could have been done (more elegantly...?) by producing an Interface,
    but I think the main problem principle is still untouched by this potential lack of elegancy(?))
    1) This problem should not be unknown to you experts out there,
    how is it generally and/or most elegantly solved?
    The "*** UC2: Variant 2" is the solution I would like best, had it only worked.
    2) And why arent "*** UC2: Variant 2" and
    "*** static UC2: Variant 2" working,
    while "*** Main: Variant 2" is?
    3) And a mal-apropos:
    Why can't I catch the NoClassDefFoundError?
    The output:
    *** Main: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** Main: Variant 2 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** Main: Variant 2 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** UC1: Variant 1 JAR 1 ***:
    Entering TestClass1.testMethod() packaged in JAR1.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR1.jar
    *** UC1: Variant 1 JAR 2 ***:
    Entering TestClass1.testMethod() packaged in JAR2.jar
    About to instantiate TestClass2 with the new operator
    About to call TestClass2.testMethod()
    Entering TestClass2.testMethod() packaged in JAR2.jar
    *** static UC2: Variant 2 JAR 1 ***:
    Exception in thread "main" java.lang.NoClassDefFoundError: TestClass1
            at UC2.runFromJarVariant2_static(UC2.java:56)
            at TestClassPathMain.main(TestClassPathMain.java:52)
    TestClassPathMain.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class TestClassPathMain {
        public static void main(final String args[]) throws MalformedURLException, ClassNotFoundException, InstantiationException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
                // Commented out because I cannot catch the NoClassDefFoundError.
                // Why?
                try {
                    final TestClass1 testClass1 = new TestClass1();
                    System.out.println(
                        "\nThe class TestClass1 is of some unexplicable reason available." +
                        "\nFor the purpose of the test, it shouldn't have been!" +
                        "\nExiting");
                    System.exit(1);
                } catch (NoClassDefFoundError e) {
                    System.out.println("\nPositively confirmed that the class TestClass1 is not available:\n" + e);
                    System.out.println("\n\nREADY FOR THE TEST: ...");
                // Works fine
                System.out.println("\n*** Main: Variant 1 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 1 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                System.out.println("\n*** Main: Variant 2 JAR 1 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** Main: Variant 2 JAR 2 ***:");
                runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Works fine
                final UC1 uc1 = new UC1();
                System.out.println("\n*** UC1: Variant 1 JAR 1 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC1: Variant 1 JAR 2 ***:");
                uc1.runFromJarVariant1("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                System.out.println("\n*** static UC2: Variant 2 JAR 1 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** static UC2: Variant 2 JAR 2 ***:");
                UC2.runFromJarVariant2_static("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
                // Crashes
                final UC2 uc2 = new UC2();
                System.out.println("\n*** UC2: Variant 2 JAR 1 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP1/JAR1.jar");
                System.out.println("\n*** UC2: Variant 2 JAR 2 ***:");
                uc2.runFromJarVariant2("file:/W:/java/eclipse/workspaces/simped_test/CP2/JAR2.jar");
        private static void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
        private static void runFromJarVariant2(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    UC1.java
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC1 {
        public void runFromJarVariant1(final String jarFileURL)
            throws MalformedURLException,
                   ClassNotFoundException,
                   InstantiationException,
                   IllegalArgumentException,
                   IllegalAccessException,
                   InvocationTargetException,
                   SecurityException,
                   NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final Object testClass1 = clazz.newInstance();
            final Method testMethod1 = clazz.getMethod("testMethod", null);
            testMethod1.invoke(testClass1, null);
    UC2.java
    import java.lang.reflect.InvocationTargetException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLClassLoader;
    public class UC2 {
        public void runFromJarVariant2(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
         * Identic to the "runFromJarVariant2" method,
         * except that it is static
        public static void runFromJarVariant2_static(final String jarFileURL)
        throws MalformedURLException,
               ClassNotFoundException,
               InstantiationException,
               IllegalArgumentException,
               IllegalAccessException,
               InvocationTargetException,
               SecurityException,
               NoSuchMethodException {
            final URL url = new URL(jarFileURL);
            final URLClassLoader cl =
                new URLClassLoader(new URL[]{url},
                                   Thread.currentThread().getContextClassLoader());
            final Class clazz = cl.loadClass("TestClass1");
            final TestClass1 testClass1 = new TestClass1();
            testClass1.testMethod();
    }

    2. i need to load the class to the same JVM (i.e. to
    the same environment) of the current running
    aplication, so that when the loaded class is run, it
    would be able to invoke methods on it!!!
    ClassLoader(s) do this. Try the URLClassLoader.
    (I was talking about relatively esoteric "security"
    issues when I mentioned the stuff about Class objects
    "scope".) You might use the URLClassLoader kind of
    like this.
    Pseudo-code follows:
    // setup the class loader
    URL[] urls = new URL[1];
    urls[0] = new URL("/path/to/dynamic/classes");
    URLClassLoader ucl = new URLClassLoader(urls);
    // load a class & use make an object with the default constructor
    Object tmp = ucl.loadClass("dynamic.class.name").newInstance();
    // Cast the object to a know interface so that you can use it.
    // This may be used to further determine which interface to cast
    // the class to. Or it may simply be the interface to which all
    // dynamic classes have to conform in your program.
    InterfaceImplementedByDynamicClass loadedObj =
        (InterfaceImplementedByDynamicClass)tmp;It's really not as hard as it sounds, just write a little test of
    this and you will see how it works.

  • Application builder and dynamic class VIs name collision

    I'm, using LabView 8.6 and I'm trying to make executable file. 
    The application builder returns warning:  
    "LabVIEW prevented a file name collision during the build. Duplicate file names cannot be copied to the same destination. You can rename files as part of the build process to avoid name conflicts."
    ...and no executable is created.
    I'm pretty sure the warning comes from the fact that I use dynamic class member VIs, that are by definition have to have same names in both parent and children.    
    The following link (http://zone.ni.com/reference/en-XX/help/371361E-01/lvhowto/caveats_apps_dlls/) says " If you don't rename the files, Application Builder moves the files to different folders for you to avoid a filename collision.", but no folders are created.
    Any help here? 

    Hi,
    If you have a parent class and one or more child classes, during the build LV will create a folder for each class with a conflicting VI.  The offending VIs will be dumped in their respective folders, resolving the conflict.  For what it's worth, I've used dynamic dispatch VIs several times in executables in LV 8.6 without seeing the issue you're reporting.
    My only advice would be to:
    1) make sure that you haven't somehow put two VIs of the same name in the same class (not even sure that's possible).
    2) make sure you aren't renaming a VI during the build and creating a conflict
    JasonP - CLD

  • How to get the class name and field name dynamically

    Hi
    I have a class (ex: Contract) the fields (ex : a,b,c) .i need to get the class name and field name dynamically
    ex
    if( validation file for the field Contract.a){
    return contract.a;
    }else if(validation file for the field Contract.b){
    return contract.b;
    how to pass the field name and object dynamically
    Please help me .............
    Thanks in Advance..
    Edited by: 849614 on Aug 11, 2011 6:49 AM

    YoungWinston wrote:
    maheshguruswamy wrote:
    Agreed, but IMO, i still feel its best if there is no tie in between consumer class level details and the database it talks to. A service layer is needed in between them.Sounds like you've done a bit of this before. Me, I've either been a modeller/DBA, doling out data, or a nuts and bolts programmer (and actually more toolmaker than apps, but did a bit of that too).
    Do you know of a good book about the "middle ground" (ie, these service layers)? I understand it empirically, but haven't had a lot of exposure to it.
    Winston
    Edited by: YoungWinston on Aug 11, 2011 10:34 PM
    PS: Apologies. Edited my previous post, presumably while you were composing your reply, when I finally realized what '.filed' meant.Most of my work is in web development, never been a DBA :) . The biggest 'concern' in my shop is 'separation of concerns'. The UI group reports up to a different IT head, the DB group reports up to a different IT head and so on. The looser the coupling between these systems, the lesser the project costs (Integration, QA etc) are. Martin Fowler's books contain good information about separation of concerns in an enterprise environment. The two books which i recommend are
    [url http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420]Enterprise Application Architecture and
    [url http://www.amazon.com/Enterprise-Integration-Patterns-Designing-Deploying/dp/0321200683/ref=pd_sim_b_1]Enterprise Integration Patterns

  • Where should the support classes of servlets, JSPs and EJBs be placed

              Hi
              Could you please tell me where the support classes (simple
              java classes) used by servlets, JSPs and EJBs should be placed.
              I find that my application does not work if I place all the
              support classes of a servlet under $MYSERVER/clientclasses. I need to place some in $MYSERVER/clientclasses and some in
              $MYSERVER/servletclasses. But I figured this out my trial and error and I could not find any logical explanation why some of them should go into $MYSERVER/clientclasses and others into
              $MYSERVER/servletclasses.
              Thanks
              Regards
              Pratima
              

    you can put 'em in weblogic classpath
              Kumar
              Pratima Nambiar wrote:
              > Hi
              > Could you please tell me where the support classes (simple
              > java classes) used by servlets, JSPs and EJBs should be placed.
              > I find that my application does not work if I place all the
              > support classes of a servlet under $MYSERVER/clientclasses. I need to place some in $MYSERVER/clientclasses and some in
              > $MYSERVER/servletclasses. But I figured this out my trial and error and I could not find any logical explanation why some of them should go into $MYSERVER/clientclasses and others into
              > $MYSERVER/servletclasses.
              >
              > Thanks
              > Regards
              > Pratima
              

  • Shared classes between webapplication and ejb

    Hello,
    If I have some java classes that are used by both WebApplication and EJB, do
    I have to include those classes into both war and jar files?
    Regards,
    Peter

    Yes accorinding to WLS Documentation
    --Naggi
    "Programming today is a race between software engineers
    striving to build bigger and better idiot-proof programs, and the universe
    trying to build bigger and better idiots.
    So far, the universe is winning."
    "Peter Tsang" <[email protected]> wrote in message
    news:[email protected]..
    >
    Hello,
    If I have some java classes that are used by both WebApplication and EJB,do
    I have to include those classes into both war and jar files?
    Regards,
    Peter

Maybe you are looking for

  • AIO no longer compatible with windows 8.1

    I have an HP AIO 8500 that I used to love.  After a recent windows update, I get the following I have completed ALL steps at LEAST 4 times, to no avail. I am ready to chuck this thing out the window. Any other suggestions?

  • How to transfer Internal table to a Adobe form? ....urgent...

    Hi Experts, I am not able to get the data in the adobe form from an internal table. I need to put the data in individual fields in the adobe form. I'm working on Adobe Interactive form developed in WDP ABAP.( I have successfully config the ADS in my

  • Iphoto 08 won't open - crashes, how to get photos out

    we have iphoto 08 and i can't open it, just spits up an error message. I don't think we've changed anything on since i last used it so i don't understand why it doesn't work. I've tried the command+option key to rebuild the library and that also just

  • MBP vibrating after HD change

    Hi,. I recently upgraded my internal MBP HD from the stock 250 Gb 5400 RPM to a seagate 500 Gb 7200 RPM. For faster speed and more room to edit HD movies, for one thing... The problem I have is that I always feel a vibration coming from the HD. This

  • Anti-**** software for Mac

    I'm sorry, for some reason I was unable to post in other forums right now, and I wasn't sure exactly where I'm supposed to go to ask about this.... Can anyone recommend a software for Mac that blocks all **** and **** related websites? It would be id