Call Bean from normal java class

Dear Friends,
Is it ok to call an entity bean or session bean frm normal Java class.
(Java class is in the same application as the beans).
Is there a special way to lookup the beans from normal java classes.
Thanking You,
Chamal.

it is ok and very commonly done.
Note that the simple java program must be running in the same local network. You cannot have the java program and EJBs distributed over internet. (I m not certain of it, but mostly I shoudl be correct. If you have the resources, try it out and let me know)
In most of the cases, EJBs are called by
1. A servlet
2. Another EJB
3. a simple java program.
In the first 2 cases, you can go for Local Interfaces (more so in the second case than the first). The reason being that the the client and server will be in the same JVM (typically the Application server). Thus, in the first case, if the Web container and the ejb container are in the same app server, EJBs can be local.
However, in the third case, it is unlikey that you will have the client runnng and the same jvm as the server, because the app server has its own jvm.
sample code (this method is being called from the main method of a simple java program. it is self explanatory):
public  void processRequestForSessionBean()
         System.out.println("REQUEST RECEIVED");
         try
               Hashtable nameHashtable = new Hashtable();
               nameHashtable.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );
               nameHashtable.put( Context.PROVIDER_URL, "t3://localhost:7001" );
               InitialContext context = new InitialContext(nameHashtable);
               System.out.println("created initial context");
               Object lookupObject = context.lookup("CustomerBean");
               System.out.println("Got the lookup object");
               CustomerDataHome home = (CustomerDataHome) PortableRemoteObject.narrow(lookupObject,
                         Class.forName("com.shiv.business.CustomerDataHome"));
               System.out.println("Home interface");
               customerData = home.create();
               System.out.println("Remote Interface");
               addDataToSB(customerData);
               ArrayList namesList = customerData.getNames();
               System.out.println(namesList.toString());
               //customerData.remove();             
          catch (Exception exception)
               System.out.println("FATAL ERRORS");
               exception.printStackTrace();
          }

Similar Messages

  • How to get properties of a bean from another java class

    Hi,
    I am new to JSF. Currently I am facing a problem, and hope you experts can give me some guidance.
    The JSF app i am working on has one Java class for handling a tree structure, MyTreeNode.java, and it also has a bean, NameBean.java, which has two properties, username and password.
    I can easily associate an input text with the #{name.username} to store the user's login... but later on, I need to fetch that information inside of MyTreeNode.java. How do I do that? Thanks!
    -- Jim

    <managed-bean>
         <managed-bean-name>Person</managed-bean-name>
         <managed-bean-class>demo.PersonBean</managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
         <managed-property>
              <property-name>bank</property-name>
              <property-class>demo.BankBean</property-class>
              <value>#{bank}</value>
         </managed-property>
    <managed-bean>
    <managed-bean>
         <managed-bean-name>bank</managed-bean-name>
         <managed-bean-class>demo.BankBean</managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
    <managed-bean>this version doesnt work for me.
    does the single beans have to look any special?
    some demo code out there?
    thx!

  • Calling Servlet from a java class

    Hi,
    I don�t know what I�m doing wrong...
    I try to call a servlet located in a tomcat webserver, from a class, and capture its output. I use an URLConnection object... Everything is all right when I want to get an html page, but, it reports an IOException (FileNotFoundException) when the requested resource is a servlet.
    This servlet is working correctly.
    Can�t I use an URLConnection to access servlets?
    Cheers

    try setting up the user agent property of HTTP protocol to a browsers,its worth a shot.
    Cheers
    Khalid

  • How can I call a pop up window from a java class ?

    Hi,
    I am developing a web app. I would like to call a windoz pop up from a java class.
    How can i do that ?
    Thanks

    user504072 wrote:
    It was possible to do it in ASP .NET even from the server side with the method Page.ClientScript. What do you think what Page.ClientScript stands for?
    I's an encapsulation for the JavaScript code required and hides the separation between frontend and backend. There was a reason why so many developers stick to the MVC-pattern wich ist violated here.
    I did not know it is not possible to do the same thing in Java.I'ts not a task of the backend to layout the user interaction GUI.
    bye
    TPD

  • How to call a Java class from another java class ??

    Hi ..... can somebody plz tell me
    How to call a Java Class from another Java Class assuming both in the same Package??
    I want to call the entire Java Class  (not any specific method only........I want all the functionalities of that class)
    Please provide me some slotuions!!
    Waiting for some fast replies!!
    Regards
    Smita Mohanty

    Hi Smita,
    you just need to create an object of that class,thats it. Then you will be able to execute each and every method.
    e.g.
    you have developed A.java and B.java, both are in same package.
    in implementaion of B.java
    class B
                A obj = new A();
                 //to access A's methods
                 A.method();
                // to access A's variable
                //either
               A.variable= value.
               //or
               A.setvariable() or A.getvariable()

  • Any difference in creating a web service from a java class or session bean?

    Hi,
    The JDeveloper tutorial at http://www.oracle.com/technology/obe/obe1013jdev/10131/devdepandmanagingws/devdepandmanagingws.htm demonstrates creating a web service from a plain java class. I'm wondering:
    - Is it possible to create a web service from a stateless session bean instead of a java class? If so, what's the proper way to do this in JDeveloper? When I tried doing so in JDeveloper 10.1.3.0.4 (SU5) using the J2EE Web Service wizard, the wizard did not list the session bean in the Component To Publish dropdown (it does list any java classes available in the project). I can proceed by manually typing in the name of the session bean. After the wizard completes though, the @Stateless annotation that had been in my session bean class code is removed and replaced by a @WebService annotation. The end result is that it looks like it made no difference whether I had tried to create the web service from a session bean or plain java class as the annotations in the resulting web service code are the same (although if I had started from a session bean, the class for the web service still implements the Local/Remote EJB interface that the session bean originally implemented).
    - Assuming it's possible to create a web service from a stateless session bean, is there any advantage/disadvantage creating a web service from a java class vs a stateless session bean? I'm creating the web service from scratch so I also need to either build the java class or stateless session bean the web service would be based on from scratch too.
    Thanks for any ideas about this.

    Hi,
    EJB Session beans (EJB 3.0) are deployed as WebServices by annotating the class with @WebService and the methds with @WebMethod (both tags require you to add the JSR-181 library to your project (available in the JDeveloper list of libraries)). Unlike the J2E WebService, the EJB session bean service is turned into a WebService upon deployment. This means you obtain teh WSDL file after deployment
    - Assuming it's possible to create a web service from a stateless session bean, is there any advantage/disadvantage creating a web service from a java class vs a stateless session bean?
    The difference is that EJB Session bean based web services are integrated with the J2EE container, which means that they can leverage container services like transaction handling, data sources, security, JMS etc.
    Frank

  • Accessing managed-beans property from simple java class

    I have managed bean that is registered in faces-config.xml:
    <managed-bean>
    <managed-bean-name>documentReportsBean</managed-bean-name>
    <managed-bean-class>[myApp].beans.DocumentReportsBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    I want to access property of documentReportsBean from other java class without registering managed-property in faces-config. How can I do that?

    Thank you, what I needed was someone saying the right word. "ValueBinding" in this case.. :)
    Two lines:
    ValueBinding vb = FacesContext.getCurrentInstance().getApplication().createValueBinding("#{documentReportsBean}");
    DocumentReportsBean pbean = (DocumentReportsBean) vb.getValue(FacesContext.getCurrentInstance());
    gives my full control. Nice

  • Access a normal java class from EJB

    how can i access normal java class from an EJB.
    I do not want to write the business logic inside the EJB. How can I achieve this.

    There's no special API for doing this. Just use normal java. E.g.
    @Stateless
    public class FooBean implements Foo {
    public void foo() {
    // access non-EJB utility class Bar
    Bar b = new Bar();
    b.bar();
    }

  • Calling another java class from a java class

    Hi Friends,
    I have a class tht works in 2 modes,depending upon which mode i am passing (gui or text) on the command line eg:
    java myclass [mode]
    I want to call this command from another java class,and i wrote this code:
    try
             Process theProcess =
                Runtime.getRuntime().exec("java myclass  "+args[0]);
          catch(IOException e)
             System.err.println("Error on exec() method");
             e.printStackTrace();
          }When i pass "gui" it works fine,but when i pass"text", the class completes and nothing shows up on the command prompt window,so can please somebody tell me how to make this work.
    Thanks

    As aniseed just pointed out, you could do something like this:
    import javax.swing.*;
    class Test extends JFrame {
         public Test(String title) {
              this.setTitle(title);
              this.pack();
              this.setSize(300, 300);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public static void main(String[] argv) { new Test(argv[0]).setVisible(true); }
    public class Test2 {
         public static void main(String[] argv) {
              Test.main(argv);
    }Run it by executing this command:
    java Test2 "Title of Frame"See if that's not what you're looking for ...

  • Using normal java classes to access database

    Dear friends,
    Is it a good practice to make database calls from a normal java class within J2EE environment.
    What I meant by a normal java class is a class which is not an enterprise bean.
    Best Regards,
    Chamal.

    it is quite normal.
    If you make your own DAOs, it may not be efficient/generic.
    JSP/Servlets can use Hibernate (which is a set of POJOs) to access DB. Thus you have a J2EE environment using a very matured DB access methodoloy, and doing away with Enterprise bean.
    regards

  • In terms of scalabilty, will static method in normal java class better than

    You only have one copy of the static method in memory, but you have a few copy of the stateless session bean, plus the overhead of those session bean.So isn't static method of normal java class more scalable than stateless session bean.

    Then you have to take care of transaction management, connection pooling, etc other ejb services all by your self.
    In fact stateless session beans acts more like a static class. They do not get destroyed when remove() method is called on client stub. Similarly they are not always gets created whenever someone calls create() method on home interface!! (Again it's specific to appserver implementation)
    Thx.

  • Calling JPA from a Java Stored Procedure

    Is it possible to call JPA from a java stored procedure? If so, does anyone have example? How do you setup the persistence.xml?
    How does the peformance compare with straight JDBC in a java stored procedure?
    Thanks for any help!
    Johnny

    Hi Johnny:
    Basically you can run any JDK 1.5 framework inside your Oracle 11g JVM, I have experience integrating Lucene IR library as a new [Domain Index for Oracle 11g/10g|http://docs.google.com/View?id=ddgw7sjp_54fgj9kg] .
    I am not familiar with JPA internals but my advice is howto handle the connection inside the OJVM and the configuration files.
    Some time ago I took a look to SpringFramework integration and I found that writing a new ApplicationContext class which handles the loading of beans.xml from XMLDB repository instead a file should be enough to work.
    Another important point is the life cycle of the [Oracle internal JVM|http://download.oracle.com/docs/cd/E11882_01/java.112/e10588/chtwo.htm#BABHGJFI]. Unlike an standard JVM the OJVM is created once you first connect from the middle tier at OCI level and remains in execution during the connection pool existence.
    I mean, if you connect using a JDBC pool the JVM will remains running across multiple soft open/close connections of your middle tier application. This is good because you can read your persistence.xml file using a Singleton class and this expensive operation will be re-used by multiple open/close operation done from the middle tier.
    I suggest you do a simple Proof of Concept with a Hello World application and check if it works.
    Remember that any security issues will be notified to the .trc files, security issues are related to the strong security layer configured by default inside the OJVM, for example you can not read any files from the OS file system without an specific grant, you need another grant to access to the class loader and so on, but you can simply grant this specific needs to a database role and then grant this role to the user which connect to the OJVM.
    Another important point is related to the [End-of-Call Optimization|http://download.oracle.com/docs/cd/E11882_01/java.112/e10588/chtwo.htm#BABIFAAI] this can be useful if you want to perform some clean up in your Singleton class at the level of per-statement execution.
    Best regards, Marcelo

  • Call EJB from Start Up class

    I'm using OC4J 10.1.3 Standalone.
    I have a requirement to initialize web services and configuration parameters during app server start up.
    Accordingly,I planned to call a EJB 2.0 stateless session bean from a StartUp class.
    The ejb is responsible for initializing some configurations and web services.The ejb is dependent on some other classes which are present as utility jars .
    However,I cannot somehow figure out how to refer the EJB from my startup class because the EAR which contains the EJB jar is in a child loader to that containing the startup class.
    Please guide me!! Please suggest if some alternative approach could be taken to suffice my requirement.
    TIA

    Avi, I was just waiting for the "servlet hack".
    I really prefer the application client way, much cleaner, no servlet container needed, and could be tested outside the container.
    --olaf                                                                                                                                                                                                                                                                                                                                                                                       

  • Calling a servlet in java class

    Hello,
    I try to call a servlet from java class
    but is dose not work
    what should be the problem
       public void callServlet()
              try
                            // xxservlet is the servlet name
                   URL url = new URL("http://www.mydomain.com/xxservlet");
                   URLConnection hpCon = url.openConnection();
                   hpCon.setDoOutput(true);
                   OutputStreamWriter out = new OutputStreamWriter(hpCon.getOutputStream());
                   out.write("This Is a Test");
                   out.flush();
                   out.close();
              }catch(Exception ex){ex.printStackTrace();}     
    // My Servlet  is in package servlets
    public class XXServlet extends HttpServlet
        public void service(HttpServletRequest req, HttpServletResponse resp) {
            try {
                 ServletInputStream sin = req.getInputStream();
                 int len = req.getContentLength();
                    byte[] input = new byte[len];
                    ServletInputStream sin = req.getInputStream();
                   int c, count = 0 ;
                   while ((c = sin.read(input, count, input.length-count)) != -1) {
                       count +=c;
                  sin.close();
                  String inString = new String(input);
                  System.out.println("Servlet is running ...."+inString);
            } catch (IOException e) {
                try{
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    resp.getWriter().print(e.getMessage());
                    resp.getWriter().close();
                } catch (IOException ioe) {
    // web.xml
    <servlet>
           <servlet-name>xxservlet</servlet-name>
           <servlet-class>servlets.XXServlet</servlet-class>
        </servlet>
       <servlet-mapping>
        <servlet-name>xxservlet</servlet-name>
        <url-pattern>/xxservlet</url-pattern>
      </servlet-mapping>
    }regards
    Edited by: the_Orient on Mar 30, 2009 3:16 AM

    I have start servlet from brwoser only to test that servlet works fine
    A gain what I need
    I want to call a servlet from a javs class
    URL url = new URL("http://www.mydomain.com/myservlet");
      URLConnection hpCon = url.openConnection();
      hpCon.setDoOutput(true);
      OutputStreamWriter out = new OutputStreamWriter(hpCon.getOutputStream());
      out.write("Hello Woprld");
      out.flush();
      out.close();// Servlet
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
            try {
                  String xp =req.getSession().getServletContext().getRealPath("/");
                  File f = new File(xp+"/students/info.txt");
                  f.createNewFile();
            } catch (IOException e) {
                try{
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    resp.getWriter().print(e.getMessage());
                    resp.getWriter().close();
                } catch (IOException ioe) {
    problem file can not be created
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
    }I hope that is clear

  • How to execute a jsp instruction from a java class?

    How to execute a jsp instruction from a java class?
    Any help please.
    Thank's

    I'll detail my problem:
    Supposing that I have a jsp file called: start.jsp
    In the start.jsp I instanciated an object called global from the class Global ( for example ).
    Then, I called a custom taglib:
    <ix:mytag/>
    In the suitable tld file: the mytag is defined:
    <tag>
    <tag class>Tag1<.....
    The java file Tag1 has method:
    doStartTag(){
    // here is the problem
    global.doSomeFunctions();
    Okay, the problem is that the object gobal is not defined in the class Tag1. what to do?
    I think that I have to pass the object global as a parameter to the class Tag1. How to do that?
    Actually, the problem was to insert the follwoing in the doStartTag method:
    doStartTag(){
    pageContext.getOut().print("<%= hello world %>");
    The output is <%= hello world %> not hello world.
    Okay, the new problem is how to pass an object as a parameter to a class called from a tld file.
    Any help please.
    Thank's too much

Maybe you are looking for

  • Problem starting LR on Windows 7 PC (x64)

    Hello: I was wondering if someone is having the same problem with Lightroom 2.5 (x64): After installing LR on a Windows 7 PC (x64), the desktop shortcut is not working. I have tried deleting the shortcut and creating a new one, tried to start LR dire

  • What's wrong with my plist file?

    Here's my plist file     <?xml version="1.0" encoding="UTF-8"?>     <!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >     <plist version="1.0">     <dict>       <key>Label</key>       <string

  • IP addresses.

    How can I get IP addresses of client and host in a web application. Not just in servlets, I want to know how to get these values in a simple java class. Thanks,

  • Sending email copy to myself on E52

    I'm pretty sure that in my previous phone (6120) there was an email setting "Send copy to myself" or something.. Now I'm wondering how to config that on E52.. I have gone through all (?) the email settings and user manual without luck. I'm using IMAP

  • How do I get rid of the "Will you help improve Mozilla Firefox...." bar so it doesn't appear EVERY TIME i start Firefox?

    I do not wish to participate in that program, so I want the question bar permanently removed.