One of the joys of C/C++ is pointers. However, reading complicated C/C++ definitions and function pointers can be a nightmare. Here are some steps to help you read C/C++ pointers and function pointers.
Start at the variable name (or innermost construct if no identifier is present). Look right without jumping over a right parenthesis; say what you see. Look left again without jumping over a parenthesis; say what you see. Jump out a level of parentheses if any. Look right; say what you see. Look left; say what you see. Continue in this manner until you say the variable type or return type.
int *foo[100];
foo is an array of hundred of pointers to int
int (*(*fp)[])();
fp is a pointer to an array of pointers to functions that return ints.
char *( *(**fp [][100]) () )[];
fp is an array of an array of 100 of pointers to pointers to functions that return an array of pointers to char
void (*fp[10]) (void (*)() )
fp is an array of 10 pointers to functions that return void that take a pointer to a function that returns a void as a parameter.
Declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
char *(*(*a[N])())()
Back C++ home | Home
Programming tutorials, examples and code snippets. C++, Java, Perl, PHP and javascript. Enterprise examples using javaEE, JNDI and Beans. Core tutorials using sockets, threads, database, IPC, XML etc. Web 2 widgets using javascrpt. Simple easy to understand step by step tutorials,
C++ Quiz
I've selected the best of the best questions around the internet and brought them all home. Good variety of questions that wont insult your intelligence and make you think. Lets start. GO! Similar to IKM, Brainbench and PreVisor questions. Prepare yourself!
What are the 3 automatically generated functions for any class(The three amigos)?
Answer
Look at the template definitions below.
Which function gets called at (F) ?
(1) A
(2) B
(3) C
(4) D
(5) E
(6)Wont compile / compiler dependent.
Answer
What is the value of the expression 5["abcdef"] ? Does it even compile?
Answer
In which order are the destructors called?
(1) A and then B
(2) B and then A
(3) A only
(4) B only
(5) Wont compile
Answer
Given that #define sum(a,b) a+b what is the value of: 5*sum(3+1,2);
(1) 30
(2) 18
(3) 22
(4) None of the above
(5) Implementation dependent
Answer
What is displayed?
(1) Outputs '1'
(2) Outputs '2'
(3) Outputs some rubbish value
(4) Will not compile or compiler dependent
Answer
What gets called at (C) and (D) respectively?
(1) B and B
(2) A and B
(3) B and A
(4) A and A
Answer
What is the final value of 'v'?
Answer
Destructors
What is the output of the above code snippet?
(1) XYZ
(2) ZYX
(3) ZXY
(4) YXZ
Answer
Constructors
What is the output of the above code snippet?
(1) XYZ
(2) XZY
(3) XZ
(4) YXZ
Answer
Back C++ home | Home
What are the 3 automatically generated functions for any class(The three amigos)?
Answer
Look at the template definitions below.
1. template <typename T> 2. class FOO{ 3. public: 4. int B(T t); //(A) 5. int B(int i); //(B) 6. int B(int i) const; //(C) 7. }; 8. 9. template<> 10. class FOO<bool>{ 11. public: 12. int B(int i); //(D) 13. int B(int i) const; //(E) 14. }; 15. 16. int main() { 17. const FOO<bool> f; 18. f.B(10); //(F) 19. }Hide line numbers |
(1) A
(2) B
(3) C
(4) D
(5) E
(6)Wont compile / compiler dependent.
Answer
What is the value of the expression 5["abcdef"] ? Does it even compile?
Answer
1. class base{ 2. public: 3. ~base(){} //(A) 4. }; 5. class child: public base{ 6. public: 7. ~child(){} //(B) 8. }; 9. 10. int main(){ 11. base * b = new child(); 12. delete b; 13. }Hide line numbers |
(1) A and then B
(2) B and then A
(3) A only
(4) B only
(5) Wont compile
Answer
Given that #define sum(a,b) a+b what is the value of: 5*sum(3+1,2);
(1) 30
(2) 18
(3) 22
(4) None of the above
(5) Implementation dependent
Answer
1. void allocateme(int* p){ 2. p = new int; 3. *p = 2; 4. } 5. 6. int main(){ 7. int i = 1; 8. allocateme(&i); 9. std::cout<<i; 10. return 0; 11. }Hide line numbers |
(1) Outputs '1'
(2) Outputs '2'
(3) Outputs some rubbish value
(4) Will not compile or compiler dependent
Answer
1. class a{ 2. public: 3. virtual void show(){} //(A) 4. }; 5. class b: public a{ 6. public: 7. virtual void show(){} //(B) 8. }; 9. class c{ 10. public: 11. void f(a* ap){ 12. ap->show(); 13. } 14. void f(b* ab){ 15. ab->show(); 16. } 17. }; 18. int main(){ 19. a* px = new b(); 20. c* pc = new c(); 21. px->show(); //(C) 22. pc->f(px); //(D) 23. }Hide line numbers |
(1) B and B
(2) A and B
(3) B and A
(4) A and A
Answer
What is the final value of 'v'?
1. int m=0,v=0; 2. 3. for(m=5;m>0;){ 4. v=v+(m++)+(++m); 5. m=m-3; 6. } 7. 8. cout<<v<<endl;Hide line numbers |
Answer
Destructors
1. class X{ 2. public: 3. ~X(){ 4. cout<<"X"; 5. } 6. }; 7. class Y{ 8. public: 9. ~Y(){ 10. cout<<"Y"; 11. } 12. }; 13. class Z: public X{ 14. Y y; 15. public: 16. ~Z(){ 17. cout<<"Z"; 18. } 19. }; 20. 21. int main(int argv, char** argc){ 22. Z* z = new Z(); 23. delete z; 24. }Hide line numbers |
(1) XYZ
(2) ZYX
(3) ZXY
(4) YXZ
Answer
Constructors
1. class X{ 2. public: 3. X(){ 4. cout<<"X"; 5. } 6. }; 7. class Y{ 8. public: 9. Y(){ 10. cout<<"Y"; 11. } 12. }; 13. class Z: public X{ 14. Y y; 15. public: 16. Z(){ 17. cout<<"Z"; 18. } 19. }; 20. 21. int main(int argv, char** argc){ 22. Z* z = new Z(); 23. delete z; 24. }Hide line numbers |
(1) XYZ
(2) XZY
(3) XZ
(4) YXZ
Answer
Back C++ home | Home
Cplusplus C++ Home
Your one resource for all things C++ -windows and Linux- including the soon to be legendary never ending C++ Quiz. From C++ basics such as templates, virtual functions and diamond inheritance to advances topics such as forking, sockets, pipes and semaphores. Let the fun commence! Windows and Linux included! Usually use g++ on Linux and Viasual C++'s cl.exe on windows.
Linux Sockets, Threads, Forking etc
Linux C++ Socket Example with Client Server and Mulit-Threading
Linux C++ Forking Server and Client Socket Example
Windows Sockets, Threads etc
C++ Winsock Example Using Client Server and Multi-Threading
Windows C++ Producer Consumer Threaded Example
Windows System
Simple Windows C++ DLL Example with Implicit and Explicit Calls
Windows C++ Get CPU and Memory Utilisation Using Windows Performance Counters
Creating, releting and Enumerating Windows Registry
General C++
How To Read Nasty Function Pointers
Using MQ C++ C API to Connect to Glassfish JMS
Dynamically Allocating Multidimentional Arrays in C++
C++ Database
MySQL Connector C++ Example - Windows cl.exe (VC++)
MySQL Connector C++ Database Connection Pool
Oracle OCCI (C++ OCI) Database Connection Pool
The never ending C++ Quiz
Linux Sockets, Threads, Forking etc
Linux C++ Socket Example with Client Server and Mulit-Threading
Linux C++ Forking Server and Client Socket Example
Windows Sockets, Threads etc
C++ Winsock Example Using Client Server and Multi-Threading
Windows C++ Producer Consumer Threaded Example
Windows System
Simple Windows C++ DLL Example with Implicit and Explicit Calls
Windows C++ Get CPU and Memory Utilisation Using Windows Performance Counters
Creating, releting and Enumerating Windows Registry
General C++
How To Read Nasty Function Pointers
Using MQ C++ C API to Connect to Glassfish JMS
Dynamically Allocating Multidimentional Arrays in C++
C++ Database
MySQL Connector C++ Example - Windows cl.exe (VC++)
MySQL Connector C++ Database Connection Pool
Oracle OCCI (C++ OCI) Database Connection Pool
The never ending C++ Quiz
J2EE and Web 2 Related Tutorials
Tutorials for enterprise java beans, web services, jms, jdbc, jndi, javascript, AJAX,s ervlets Apache struts, Apache axis, MySQL, Ant on tomcat, glassfish etc. Clear concise java based tutorials with good explanations and step by step instructions. All original.
JMS Example using Glassfish and a Remote Client
Aim
The aim of this Java Messaging Service JMS tutorial is to configure a simple JNDI JMS Topic in glassfish, publish to the topic using a serverlet and listen in on the JMS topic using a remote java client. For some reason this took a long time simply because of the number of errors I kept getting. The well documented java.lang.ClassNotFoundException: com.sun.messaging.jms.ra.ResourceAdapter among the more famous ones. Leave any questions or problems as comments and I will endeavour to answer them.
If you wish to connect to JMS using C/C++ please have a look at Connecting to Glassfish JMS using C++/C API.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is GlassfishJMSHelloWorld.
Versions used in this example
Links to these files can be found here
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishJMSHelloWorld will be referred to as your project or working directory. Create this structure.
GlassfishJMSHelloWorld
_|_src
_|__|_PublisherServlet.java
_|__|_TopicListener.java
_|_WEB-INF
_|__|_web.xml
_|__|_classes
_|_bin
_|__|_appserv-rt.jar
_|__|_imqmsra.jar
_|__|_javaee.jar
_|__|_appserv-admin.jar
_|__|_appserv-deployment-client.jar
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.
Configure the JMS ConnectionFactory and Topic in Glassfish
Write and compile the servlet
Back to the tutorial trail | Home
The aim of this Java Messaging Service JMS tutorial is to configure a simple JNDI JMS Topic in glassfish, publish to the topic using a serverlet and listen in on the JMS topic using a remote java client. For some reason this took a long time simply because of the number of errors I kept getting. The well documented java.lang.ClassNotFoundException: com.sun.messaging.jms.ra.ResourceAdapter among the more famous ones. Leave any questions or problems as comments and I will endeavour to answer them.
If you wish to connect to JMS using C/C++ please have a look at Connecting to Glassfish JMS using C++/C API.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is GlassfishJMSHelloWorld.
Versions used in this example
| Sofware/Component | Image |
| Windows XP SP2 | N/A |
| Glassfish 2 | glassfish-installer-v2.1-b60e-windows.jar |
| JDK 1.5.0 | N/A |
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishJMSHelloWorld will be referred to as your project or working directory. Create this structure.
GlassfishJMSHelloWorld
_|_src
_|__|_PublisherServlet.java
_|__|_TopicListener.java
_|_WEB-INF
_|__|_web.xml
_|__|_classes
_|_bin
_|__|_appserv-rt.jar
_|__|_imqmsra.jar
_|__|_javaee.jar
_|__|_appserv-admin.jar
_|__|_appserv-deployment-client.jar
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.
Configure the JMS ConnectionFactory and Topic in Glassfish
- Login to the admin console in you Glassfish domain (see Installing and Setting up Glassfish 2 for more details).
`
- Select Resources -> JMS Resources -> Connection Factories. Select New.
`
- Set the name as jms/MyConnectionFactory and select javax.jms.ConnectionFactory as the "Resource Type" dropdown. Select OK.
`
- Now select Resources -> JMS Resources -> Destination Resources. Select New
`
- Enter jms/MyFirstTopic as the JNDI name. Enter MyFirstTopic into the Physical Destination Name and select javax.jms.Topic from the "Resource Type" dropdown. Select OK. The physical destination is what you would use to connect outside of JNDI - forexample using the JMS C-API.
`
- Once this is done open a cmd prompt/terminal and navigate to the Glassfish asadmin directory (D:\downloads\glassfish\bin) in this example.
`
- Use the asadmin list-jndi-entities to make sure your JNDI names are visible.
d:\downloads\glassfish\bin>asadmin -list-jndi-entities --context jms
Jndi Entries for server within jms context:
MyConnectionFactory: javax.naming.Reference
MyFirstTopic: javax.naming.Reference
Command list-jndi-entries executed successfully.
- Copy these files below from your glassfish\lib directory to the bin directory under your working directory
appserv-rt.jar
appserv-admin.jar
appserv-deployment-client.jar
javaee.jar
Copy the imqjmsra.jar file from the glassfish\lib\install\applications\jmsra to the bin directory in your working directory.
This is the best way to isolate these files so you can be sure to pick up the correct one, without specifying directories.
Write and compile the servlet
- Write the servlet and save it as PublisherServlet.jar under the "src" directory in your working directory.
1. import java.io.*; 2. import java.util.*; 3. 4. import javax.servlet.*; 5. import javax.servlet.http.*; 6. 7. import javax.jms.*; 8. import javax.naming.*; 9. 10. public class PublisherServlet extends HttpServlet { 11. 12. public void doGet(HttpServletRequest request, HttpServletResponse response){ 13. try{ 14. Context context = new InitialContext(); 15. TopicConnectionFactory tfactory = (TopicConnectionFactory) context.lookup("jms/MyConnectionFactory"); 16. 17. TopicConnection tconnection = tfactory.createTopicConnection(); 18. TopicSession tsession = tconnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); 19. TopicPublisher publisher = tsession.createPublisher((Topic)context.lookup("jms/MyFirstTopic")); 20. 21. TextMessage message = tsession.createTextMessage(); 22. message.setText("Hello there buddy"); 23. publisher.publish(message); 24. 25. context.close(); 26. tconnection.close(); 27. 28. response.setContentType("text/html"); 29. response.getWriter().println("<html><body>message sent</body></html>"); 30. 31. 32. }catch(Exception e){ 33. e.printStackTrace(); 34. } 35. } 36. }
Hide line numbers
`
- Compile the code and install it using
Substitue your local glassfish\lib directory for the -extdirs.
..workspace\GlassfishJMSHelloWorld\src>javac -extdirs d:\downloads\glassfish\lib -d ..\WEB-INF\classes PublisherServlet.java
`
- Create the web.xml file in the same WEB-INF directory.
1. <?xml version="1.0" encoding="UTF-8"?> 2. <web-app> 3. 4. <display-name>GlassfishJMS sender/publisher</display-name> 5. 6. <servlet> 7. <servlet-name>Glassfish JMS Publisher</servlet-name> 8. <servlet-class>PublisherServlet</servlet-class> 9. </servlet> 10. 11. <servlet-mapping> 12. <servlet-name>Glassfish JMS Publisher</servlet-name> 13. <url-pattern>/publish</url-pattern> 14. </servlet-mapping> 15. 16. </web-app>
Hide line numbers
`
- Now cd out to the workingdirectory and jar up the WEB-INF directory using
..workspace\GlassfishJMSHelloWorld>jar -cfv glassfishjms.jar WEB-INF
- Login to you Glassfish admin console (see Installing and Setting up Glassfish 2 for more details).
`
- Select Applications -> Web Applications and select "Deploy."
`
- Under "Type" select App client(.jar). Under "Location" select "Packaged file to be uploaded to the server". Select "Browse Files" and navigate to your working directory and select the glassfishjms.jar you created in the previous step. Select OK.
`
- Now navigate to 'http://127.0.0.1:8082/glassfishjms/publish' in your browser. You should see a response saying "message sent."
- Create the TopicListerner.java file and save it under the src directory in your working directory.
1. import java.io.*; 2. import java.util.*; 3. 4. import javax.jms.*; 5. import javax.naming.*; 6. 7. public class TopicListener implements MessageListener{ 8. 9. public static void main(String args[]){ 10. new TopicListener().Go(args); 11. } 12. 13. public void Go(String[] args){ 14. try{ 15. Properties props = new Properties(); 16. props.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.appserv.naming.S1ASCtxFactory"); 17. props.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700"); 18. 19. Context context = new InitialContext(props); 20. TopicConnectionFactory tfactory = (TopicConnectionFactory) context.lookup("jms/MyConnectionFactory"); 21. 22. TopicConnection tconnection = tfactory.createTopicConnection(); 23. TopicSession tsession = tconnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); 24. 25. TopicSubscriber subscriber = tsession.createSubscriber((Topic)context.lookup("jms/MyFirstTopic")); 26. 27. subscriber.setMessageListener(this); 28. 29. tconnection.start(); 30. 31. (new BufferedReader(new InputStreamReader(System.in))).readLine(); 32. 33. context.close(); 34. tconnection.close(); 35. }catch(Exception e){ 36. e.printStackTrace(); 37. } 38. } 39. 40. public void onMessage(Message message){ 41. if(message instanceof TextMessage){ 42. try{ 43. System.out.println( ((TextMessage)message).getText()); 44. }catch(Exception e){ 45. } 46. } 47. } 48. }
Hide line numbers
`
- Compile and install the class in your bin directory
..workspace\GlassfishJMSHelloWorld\src>javac -extdirs d:\downloads\glassfish\lib -d ..\bin TopicListener.java
- Open a prompt into the bin directory and fire up the client like so.
..workspace\GlassfishJMSHelloWorld\bin>java -cp javaee.jar;imqjmsra.jar;appserv-rt.jar;appserv-admin.jar;. TopicListener
`
- Now navigate to 'http://127.0.0.1:8082/glassfishjms/publish' in your browser. You should see a response saying "message sent." The message should now magically appear in the prompt where your remote client is running.
Back to the tutorial trail | Home
Session EJB Example on Glassfish - No Annotations
Aim
The aim of this Java Session Bean tutorial is to create simple stateless (and stateful) Enterprise Java Beans or EJBs, deploy it to a Glassfish app server and then call it's remote interface via a java client. We will be building this bean from the ground up with an ejb-jar.xml and without the use of Annotations( @Remote etc). Once you learn the basic you can take the short-cuts. Leave any questions or problems as comments and I will endeavour to answer them. The sister tutorial for an Entity Bean can be found at CMP EJB Example.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is EJBHelloWorld.
Versions used in this example
Links to these files can be found here
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishWSHelloworld will be referred to as your project or working directory. Create this structure.
EJBHelloWorld
_|_bean_src
_|__|_SessionBeanExample.java
_|__|_SessionBeanHomeExampleI.java
_|__|_SessionBeanExampleI.java
_|_bean_bin
_|__|_META-INF
_|__|__|_ejb-jar.xml
_|__|__|_sun-ejb-jar.xml
_|_client_src
_|__|_SessionBeanClient.java
_|_client_bin
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.
Write and compile the Bean files
Deploy the EJB in Glassfish
We are going to take a short cut and deploy the bean_bin directory instead of jar-ring it up and deploying as a .war or .jar file.
Write and compile the Client
Running the client
Back to the tutorial trail | Home
The aim of this Java Session Bean tutorial is to create simple stateless (and stateful) Enterprise Java Beans or EJBs, deploy it to a Glassfish app server and then call it's remote interface via a java client. We will be building this bean from the ground up with an ejb-jar.xml and without the use of Annotations( @Remote etc). Once you learn the basic you can take the short-cuts. Leave any questions or problems as comments and I will endeavour to answer them. The sister tutorial for an Entity Bean can be found at CMP EJB Example.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is EJBHelloWorld.
Versions used in this example
| Sofware/Component | Image |
| Windows XP SP2 | N/A |
| Glassfish 2 | glassfish-installer-v2.1-b60e-windows.jar |
| JDK 1.5.0 | N/A |
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishWSHelloworld will be referred to as your project or working directory. Create this structure.
EJBHelloWorld
_|_bean_src
_|__|_SessionBeanExample.java
_|__|_SessionBeanHomeExampleI.java
_|__|_SessionBeanExampleI.java
_|_bean_bin
_|__|_META-INF
_|__|__|_ejb-jar.xml
_|__|__|_sun-ejb-jar.xml
_|_client_src
_|__|_SessionBeanClient.java
_|_client_bin
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.
Write and compile the Bean files
- Write the remote interface and save it under bean_src as SessionBeanExampleI.java. The 'SayHello' method will be the exposed method in this example.
1. package ejb.sessionbeanexample; 2. 3. import java.rmi.*; 4. import javax.ejb.*; 5. 6. public interface SessionBeanExampleI extends EJBObject{ 7. public String SayHello(String s) throws RemoteException; 8. }
Hide line numbers
`
- Write the home interface and save it under bean_src as SessionBeanHomeExampleI.java.
1. package ejb.sessionbeanexample; 2. 3. import java.rmi.*; 4. import javax.ejb.*; 5. 6. public interface SessionBeanHomeExampleI extends EJBHome{ 7. public SessionBeanExampleI create() throws CreateException, RemoteException; 8. }
Hide line numbers
`
- Complete the bean implementation and save it under bean_src as SessionBeanExample.java.
1. package ejb.sessionbeanexample; 2. 3. import javax.ejb.*; 4. import java.io.Serializable; 5. import java.util.*; 6. import java.rmi.*; 7. 8. public class SessionBeanExample implements SessionBean { 9. 10. private SessionContext context; 11. 12. public void ejbActivate() { 13. System.out.println("ejb - activate"); 14. } 15. 16. public void ejbRemove() { 17. System.out.println("ejb - remove"); 18. } 19. 20. public void ejbPassivate() { 21. System.out.println("ejb - passivate"); 22. } 23. 24. public void setSessionContext(SessionContext context) { 25. System.out.println("ejb - setSessionContext"); 26. this.context = context; 27. } 28. 29. public void ejbCreate () { 30. System.out.println("ejb - create"); 31. } 32. 33. public String SayHello(String s)throws RemoteException{ 34. return(s+" echo from java bean"); 35. } 36. }
Hide line numbers
`
- Compile the code and install the classes into the bean_bin using the cmd below.
..workspace\EJBHelloWorld\bean_src>javac -extdirs D:\downloads\glassfish\lib -d ..\bean_bin *.java
`
- Create the deployment descriptor ejb-jar.xml. Save this under the bean_bin/META-INF directory. For a stateful bean simply change the value in the session-type tag to "Stateful" from "Stateless."
1. <?xml version="1.0" encoding="UTF-8"?> 2. <ejb-jar> 3. <display-name>Session Bean Example</display-name> 4. <enterprise-beans> 5. <session> 6. <description>Simple session bean example</description> 7. <ejb-name>SessionBeanExample</ejb-name> 8. <home>ejb.sessionbeanexample.SessionBeanHomeExampleI</home> 9. <remote>ejb.sessionbeanexample.SessionBeanExampleI</remote> 10. <ejb-class>ejb.sessionbeanexample.SessionBeanExample</ejb-class> 11. <session-type>Stateless</session-type> 12. <transaction-type>Bean</transaction-type> 13. </session> 14. </enterprise-beans> 15. </ejb-jar>
Hide line numbers
`
- Create the sun-ejb-jar.xml file and save this under the bean_bin\WEB-INF folder too.
1. <?xml version="1.0" encoding="UTF-8"?> 2. <sun-ejb-jar> 3. <enterprise-beans> 4. <ejb> 5. <ejb-name>SessionBeanExample</ejb-name> 6. <jndi-name>ejb/sessionbeanexample</jndi-name> 7. </ejb> 8. </enterprise-beans> 9. </sun-ejb-jar>
Hide line numbers
Deploy the EJB in Glassfish
We are going to take a short cut and deploy the bean_bin directory instead of jar-ring it up and deploying as a .war or .jar file.
- Login to the Glassfish admin console. Please see Installing and Setting up Glassfish 2
`
- Under Applications->EJB Modules select deploy. Under "Location" select "Local packaged file or directory..." and select "Browse Folders". Now navigate to your working directory (EJBHelloWorld) and select the bean_bin directory and press "Choose folder." This shold deploy the bean without any issues. If there is a problem look at the server.log in the log directory in your Glassfish domain.
`
- To make sure go to the "bin" diretory under your glassfish installation and run asadmin with list-jndi-entries.
D:\downloads\glassfish\bin>asadmin list-jndi-entries --context ejb
Jndi Entries for server within ejb context:
mgmt: com.sun.enterprise.naming.TransientContext
sessionbeanexample: javax.naming.Reference
Command list-jndi-entries executed successfully.
Write and compile the Client
- Write client and save it under the client_src direcotry as SessionBeanClient.java. I have added the remove method for completeness. This will remove a "Stateful" bean but will be ignored by a "Stateless" bean. You can check out the Glassfish logs to see this.
1. import java.util.*; 2. import java.io.*; 3. import javax.naming.*; 4. 5. import ejb.sessionbeanexample.SessionBeanHomeExampleI; 6. import ejb.sessionbeanexample.SessionBeanExampleI; 7. 8. public class SessionBeanClient { 9. 10. public static void main(String[] args) throws Exception{ 11. (new SessionBeanClient()).Go(); 12. } 13. 14. public void Go() throws Exception { 15. Properties props = new Properties(); 16. 17. props.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700"); 18. props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory"); 19. 20. InitialContext ctx = new InitialContext(props); 21. 22. SessionBeanHomeExampleI beanhome = (SessionBeanHomeExampleI) ctx.lookup("ejb/sessionbeanexample"); 23. 24. SessionBeanExampleI bean = beanhome.create(); 25. 26. System.out.println(bean.SayHello("Hi Partner")); 27. 28. bean.remove(); //For statefull 29. 30. } 31. }
Hide line numbers
`
- open a promt to the "client_src" directory and Compile the code. Use the "-d" ooption to copy the class to the client_bin directory.
..workspace\EJBHelloWorld\client_src>javac -extdirs D:\downloads\glassfish\lib
-d ..\client_bin -cp ..\bean_bin SessionBeanClient.java
Running the client
- Open a command into the client_bin directory and run the application.
..workspace\EJBHelloWorld\client_bin>java -Djava.ext.dirs=D:\downloads\glassfish\lib -cp ..\bean_bin;. SessionBeanClient
`
- You should see "Hi Partner echo from java bean" in the console. Also, if you have a look at the Glassfish server.log you will be able to see what callbacks have been triggered. If you deployed the bean as a "Stateful" bean you should see "ejbRemove" getting called. If you deployed it as a "Stateless" bean then "ejbRemove" will only get called at the descretion of the container. We're now done. If you are seeing errors check the server.log.
Back to the tutorial trail | Home
Cool Tools
Need to convert your C / C++ / Java / whatever code into html formatting? Maybe you want to find out what your page rank is or you want to submit your sitemap to the search engines. This is your one stop shop!
Convert C/C++/Java code to html
Submit your sitemap to search engines - Yahoo, MSN, Bing and Ask
All the software versions used in this tutorial.
Mega Software Download Page
Convert C/C++/Java code to html
Submit your sitemap to search engines - Yahoo, MSN, Bing and Ask
All the software versions used in this tutorial.
Mega Software Download Page
Database Connection Pooling Using Glassfish and MySQL with Remote Client
Aim
The aim of this tutorial is to configure a simple JNDI MySQL database pool in glassfish and access it using a java servlet and a remote java client. Leave any questions or problems as comments and I will endeavour to answer them.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is MySQLGlassfishJNDI. This also assumes you have MySQL installed and ready to go.
Versions used in this example
Links to these files can be found here
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. MySQLGlassfishJNDI will be referred to as your project or working directory. Create this structure. PoolUser.java will be the servlet and PoolUserClient.java will be the remore client.
MySQLGlassfishJNDI
_|_src
_|__|_PoolUser.java
_|__|_PoolUserClient.java
_|_WEB-INF
_|__|_web.xml
_|__|_classes
_|_bin
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial. I have MySQL up and running with a database called test that has a table called example with 2 columns (id and data). I'm accessing this via the root user with password root. Make sure to replace these values with the ones for your table.
Configure the database pool in Glassfish
Deploying the Service
Writing and compiling the remote client
Back to the tutorial trail | Home.
The aim of this tutorial is to configure a simple JNDI MySQL database pool in glassfish and access it using a java servlet and a remote java client. Leave any questions or problems as comments and I will endeavour to answer them.
Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is MySQLGlassfishJNDI. This also assumes you have MySQL installed and ready to go.
Versions used in this example
| Sofware/Component | Image |
| Windows XP SP2 | N/A |
| Glassfish 2 | glassfish-installer-v2.1-b60e-windows.jar |
| MySQL 5.1 (no install) | mysql-noinstall-5.1.32-win32.zip |
| MySQL Connector J | mysql-connector-java-5.1.7-bin.jar |
| Java JDK 1.5.0 | N/A |
Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.
Create this webapp directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. MySQLGlassfishJNDI will be referred to as your project or working directory. Create this structure. PoolUser.java will be the servlet and PoolUserClient.java will be the remore client.
MySQLGlassfishJNDI
_|_src
_|__|_PoolUser.java
_|__|_PoolUserClient.java
_|_WEB-INF
_|__|_web.xml
_|__|_classes
_|_bin
The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial. I have MySQL up and running with a database called test that has a table called example with 2 columns (id and data). I'm accessing this via the root user with password root. Make sure to replace these values with the ones for your table.
Configure the database pool in Glassfish
- Login to the admin console in you Glassfish domain (see Installing and Setting up Glassfish 2 for more details).
`
- Select Resources -> JDBC -> Connection Pools. Select New.
`
- Set the name as MySQLPool, select javax.sql.DataSource from the "Resource Type" dropdown and select MySQL from the "Database Vendor" dropdown. Click Next.
`
- Make sure the "DataSource Classname" is showing com.mysql.jdbc.jdbc2.optional.MysqlDataSource. Click Finish.
`
- Now select the MySQLPool and select the "Additional Properties" tab on top.
`
- Search for the "Url" parameter and modify it to reflect your database
jdbc:mysql://:3306/test?user=root&password=root
Press "Save." As there is no explicit host it's considered localhost, the name of the database is test (came with install) and I'm using the root user. You can use whatever you wish. For completeness I've included an excerpt from the dump of the 'example' table.
1. CREATE TABLE `example` ( 2. `id` int(11) DEFAULT NULL, 3. `data` varchar(100) DEFAULT NULL 4. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 5. SET character_set_client = @saved_cs_client; 6. 7. -- 8. -- Dumping data for table `example` 9. -- 10. 11. LOCK TABLES `example` WRITE; 12. /*!40000 ALTER TABLE `example` DISABLE KEYS */; 13. INSERT INTO `example` VALUES (1,'one'),(2,'two'),(3,'three'); 14. /*!40000 ALTER TABLE `example` ENABLE KEYS */; 15. UNLOCK TABLES;
Hide line numbers
`
- Do not forget to copy the mysql-connector-java-5.1.7-bin.jar file to your glassfish\lib directory and restart the domain.
`
- Now click on the "General" tab at the top. Select "Ping." You should get a successful message. If not you should look at the Glassfish logs for your domain.
`
- Now select Resources -> JDBC Resources. Select "New" and under "JNDI Name" enter "jdbc/MySQLPool" and select "MySQLPool" from the "PoolName" drop down.
`
- Now go to your glassfish\bin directory and use asadmin to make sure your jndi jdbc is visible.
D:\downloads\glassfish\bin>asadmin list-jndi-entries --context jdbc
Jndi Entries for server within jdbc context:
MySQLPool: javax.naming.Reference
Command list-jndi-entries executed successfully.
- Write the servlet and save it under the "src" directory in your working directory as PoolUser.java. I have used the default database called "test" which has a table called example. Note 'test' was configured in the previous section.
1. import java.sql.Connection; 2. import java.sql.SQLException; 3. import java.sql.Statement; 4. import java.sql.ResultSet; 5. import javax.sql.DataSource; 6. 7. import javax.servlet.*; 8. import javax.servlet.http.*; 9. 10. import javax.naming.*; 11. 12. public class PoolUser extends HttpServlet { 13. 14. public static void main(String args[]){ 15. new PoolUser().doGet(null, null); 16. } 17. 18. public void doGet(HttpServletRequest request, HttpServletResponse response){ 19. try{ 20. InitialContext ctx = new InitialContext(); 21. DataSource ds = (DataSource)ctx.lookup("jdbc/MySQLPool"); 22. 23. Connection conn = ds.getConnection(); 24. Statement stmt = conn.createStatement(); 25. 26. ResultSet rs = stmt.executeQuery("select * from example"); 27. 28. response.setContentType("text/html"); 29. 30. response.getWriter().println("<html><body>"); 31. while(rs.next()){ 32. response.getWriter().println(rs.getString("id")+" "+rs.getString("data")+"<br/>"); 33. 34. } 35. response.getWriter().println("</body></html>"); 36. 37. stmt.close(); 38. conn.close(); 39. }catch(Exception e){ 40. e.printStackTrace(); 41. } 42. } 43. }
Hide line numbers
`
- open a promt to the "src" directory and Compile the code. Use the "-d" ooption to copy the class to the WEB-INF/classes directory.
..workspace\MySQLGlassfishJNDI>javac -extdirs D:\downloads\glassfish\lib PoolUser.java
-d ..\WEB-INF\classes
`
- Create the web.xml file in the same WEB-INF directory.
1. <?xml version="1.0" encoding="UTF-8"?> 2. <web-app> 3. <display-name>OpenJMS sender/publisher</display-name> 4. 5. <servlet> 6. <servlet-name>MySQL Pool User</servlet-name> 7. <servlet-class>PoolUser</servlet-class> 8. </servlet> 9. 10. <servlet-mapping> 11. <servlet-name>MySQL Pool User</servlet-name> 12. <url-pattern>/pooluser</url-pattern> 13. </servlet-mapping> 14. 15. </web-app> 16.
Hide line numbers
Deploying the Service
- Login to you Glassfish admin console (see Installing and Setting up Glassfish 2 for more details).
`
- Select Applications -> Web Applications and select "Deploy."
`
- Under "Location" select "Local packaged file or directory..." and select "Browse Folders". Now navigate to your working directory. This is MySQLGlassfishJNDI in the case of this example. Select "Choose Folder." This should deploy your application.
`
- Now navigate to 'http://127.0.0.1:8082/MySQLGlassfishJNDI/pooluser.' You should see a response depending on what data you decided to display in your servlet.
Writing and compiling the remote client
- Write the remote client and save it under the src directory as PoolUserClient.java.
1. import java.io.*; 2. import java.util.*; 3. 4. import java.sql.Connection; 5. import java.sql.SQLException; 6. import java.sql.Statement; 7. import java.sql.ResultSet; 8. import javax.sql.DataSource; 9. 10. 11. import javax.naming.*; 12. 13. public class PoolUserClient { 14. 15. public static void main(String args[]){ 16. new PoolUserClient().Go(); 17. } 18. 19. public void Go(){ 20. try{ 21. Properties props = new Properties(); 22. props.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.enterprise.naming.SerialInitContextFactory"); 23. props.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700"); 24. InitialContext ctx = new InitialContext(props); 25. 26. DataSource ds = (DataSource)ctx.lookup("jdbc/MySQLPool"); 27. Connection conn = ds.getConnection(); 28. Statement stmt = conn.createStatement(); 29. ResultSet rs = stmt.executeQuery("select * from example"); 30. 31. while(rs.next()) 32. System.out.println(rs.getString("id")+" "+rs.getString("data")); 33. 34. stmt.close(); 35. conn.close(); 36. }catch(Exception e){ 37. e.printStackTrace(); 38. } 39. } 40. }
Hide line numbers
`
- Now compile the client and install it into the "bin" directory in your working directory.
..workspace\MySQLGlassfishJNDI\src<javac -d ..\bin -extdirs D:\downloads\glassfish\lib PoolUserClient.java
`
- Copy these files below from the glassfish\lib directory to the bin directory under your working directory
appserv-rt.jar
appserv-admin.jar
appserv-deployment-client.jar
javaee.jar
Copy the imqjmsra.jar file from the glassfish\lib\install\applications\jmsra to the bin directory in your working directory.
This is the best way to isolate these files so you can be sure to pick up the correct one, without specifying directories.
`
- Now cd into the bin directory. Run the client.
You should see the result on the screen...workspace\MySQLGlassfishJNDI\bin<java -Djava.ext.dirs=. PoolUserClient.java
Back to the tutorial trail | Home.
Subscribe to:
Posts (Atom)
