Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,143,252 members, 7,780,530 topics. Date: Thursday, 28 March 2024 at 03:56 PM

Learn Java EE With Me - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Learn Java EE With Me (6117 Views)

Is It Advisable To Learn Java As My First Programming Language? / Java EE Developer And Spring Developer In Here. / SOFTWARE DEVELOPER:- Java(ee And SE) And Android/ios (2) (3) (4)

(1) (2) (3) (4) (Reply) (Go Down)

Re: Learn Java EE With Me by NaijaTroops(m): 5:00pm On Sep 26, 2016
bros i no lie u am lost
Re: Learn Java EE With Me by steinalb(m): 5:11pm On Sep 26, 2016
NaijaTroops:
bros i no lie u am lost

my other account was banned last night here, I don't know why.

where are you having issues?
Re: Learn Java EE With Me by steinalb(m): 9:13pm On Sep 26, 2016
ugwum007:

@Entity //an entity class
@Table(name = "beers"wink //for the table
@NamedQueries({
@NamedQuery(name = "Beers.findAll", query = "SELECT b FROM Beers b"wink})
public class Beers implements Serializable {
private static final long serialVersionUID = 1L;
private int id; //column id from database
private String beername; //column beername from database
private String price; //column price from database
public Beers() { // constructor
}
@Id //denotes this field as the id column and primary key
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="id"wink
public int getId() {
return id;
}
public void setId(int bid) {
this.id = bid;
}
public String getBeername() {
return beername;
}
public void setBeername(String beername) {
this.beername = beername;
}
public String getPrice() {
return price;
}
public void setPrice(String beerPrice) {
this.price = beerPrice;
}
}

I had to uncomment the bolded owing to postgresql doesn't support auto increment like mySQL. you have to add a sequence to the table.
later, I will explain how to to that.
Re: Learn Java EE With Me by steinalb(m): 9:32pm On Sep 26, 2016
New Inventory Class:

public class Inventory_Client {

BufferedReader brConsoleReader = null; // take input from console
Properties props;
InitialContext ctx;
Context remoteContext;


public static void main(String[] args) {
// TODO code application logic here
Inventory_Client IC = new Inventory_Client();
IC.tasteStatelessEJB();
}

private void tasteStatelessEJB(){
try{
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory";
props.put(Context.PROVIDER_URL, "http-remoting://localhost:8050";
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming";
props.put(Context.SECURITY_PRINCIPAL, "steinacoz";
props.put(Context.SECURITY_CREDENTIALS, "nkenna007";
props.put("jboss.naming.client.ejb.context", true);

ctx = new InitialContext(props);

}catch(NamingException ex){
ex.printStackTrace();
}

brConsoleReader = new BufferedReader(new InputStreamReader(System.in));

try{

int choice = 1;

InventoryRemote inventoryBean = (InventoryRemote) ctx.lookup("Inventory-ejb/InventoryPersistBean!inv.InventoryRemote"; //JNDI LOOKUP
System.out.println("choose right option";
while(choice != 2){
String beerName;
String beerPrice;


String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);

if(choice == 1){
System.out.println("Enter Beer Name: ";
beerName = brConsoleReader.readLine();

System.out.println("Enter Beer Price: "wink;
beerPrice = brConsoleReader.readLine();

Beers beer = new Beers();
beer.setBeername(beerName);
beer.setPrice(beerPrice);

inventoryBean.addBeer(beer); //persists beer to the database


}else if(choice == 2){
break;
}
}

List<Beers> beerList = inventoryBean.getAllBeers();
System.out.println("Beers entered so far: " + beerList.size());
int i = 0;
for(Beers ie:beerList){
System.out.println("Beer Name: " + "." + ie.getBeername() + " Price: " + ie.getPrice());
}




}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}finally{
try{
if(brConsoleReader != null){
brConsoleReader.close();
}
}catch(IOException ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}

}
Re: Learn Java EE With Me by steinalb(m): 10:21pm On Sep 26, 2016
ugwum007:

@GeneratedValue(strategy= GenerationType.AUTO)

To understand this line more, This will HELP

to create sequence for a table, use either pgAdmin III GUI or localhostphppgadmin.
- go to the sequence table, create new sequence.
- add the parameters, save.
- run this sql query; alter table table name alter column id set default nextval('sequence name'::regclass)

my table name is beers
sequence name: beers_seq

alter table beers alter column id set default nextval('beers_seq'::regclass)


To get more insight about sequence, read THIS
Re: Learn Java EE With Me by steinalb(m): 10:39pm On Sep 26, 2016
In this next section, I will be peeping into Message driven bean

A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component—an application client, another enterprise bean, or a Web component—or by a JMS application or system that does not use J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may be used to process other kinds of messages.

What Makes Message-Driven Beans Different from Session and Entity Beans?
The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces. Unlike a session or entity bean, a message-driven bean has only a bean class.

In several respects, a message-driven bean resembles a stateless session bean.
• A message-driven bean’s instances retain no data or conversational state for a specific client.
• All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.
• A single message-driven bean can process messages from multiple clients. The instance variables of the message-driven bean instance can contain some state across the handling of client messages—for example, a JMS API connection, an open database connection, or an object reference to an enterprise bean object.
When a message arrives, the container calls the message-driven bean’s onMessage method to process the message. The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the application’s business logic. The onMessage method may call helper methods, or it may invoke a session or entity bean to process the information in the message or to store it in a database. A message may be delivered to a message-driven bean within a transaction context, so that all operations within the onMessage method are part of a single transaction. If message processing is rolled back, the message will be redelivered.

When to Use Message-Driven Beans
Session beans and entity beans allow you to send JMS messages and to receive them synchronously, but not asynchronously. To avoid tying up server resources, you may prefer not to use blocking synchronous receives in a server-side component. To receive messages asynchronously, use a message-driven bean.
Re: Learn Java EE With Me by steinalb(m): 11:01pm On Sep 26, 2016
-what we do first is to create another user for the wildfly server in the applicationRealm
-Create a JMS queue with name BeerQueue
-Create our normal entity and persistence classes for persistence purposes.
-Create a Message driven bean and other files then finally deploy.
Re: Learn Java EE With Me by steinalb(m): 11:11pm On Sep 26, 2016
Creating the BeerQueue:

-open the wildfly installation folder: wildfly folder > bin folder: mine is C:\wildfly-10\bin
-open (double click) on jboss-cli.bat
-make sure your server is on and use the command connect. press enter
-type this command when it have connected: /subsystem=messaging-activemq/server=default/jms-queue=BeerQueue/:add(entries=["java:/jboss/exported/jms/queue/BeerQueue"])

- The Queue will be created and also the JNDI binding name.

the exported in the JNDI binding is meant for remote clients who don't have access to the JVM installed on the system where the server is located/running.

Re: Learn Java EE With Me by ugwum007(m): 8:43am On Sep 27, 2016
Am back from an unjust ban.
Re: Learn Java EE With Me by ugwum007(m): 1:20am On Sep 29, 2016
For the Entity class, Bean Class And other EJB Modules files(Persistence unit, Jboss-ds.xml). Copy and paste the ones from the former example, remember to create the appropriate packages.
Re: Learn Java EE With Me by ugwum007(m): 1:24am On Sep 29, 2016
Message Driven Bean class:

package com.messagebean;

import com.entity.Beers;
import com.remoteinterface.InventoryRemote_JMS;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;



@MessageDriven(name = "beerMsgHandler",
activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:/jboss/exported/jms/queue/BeerQueue"wink,
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"wink
})
public class MessageBean implements MessageListener {//implements message listener

@Resource
private MessageDrivenContext mdctx;

@EJB
InventoryRemote_JMS iB;

public MessageBean() {
}

@Override
public void onMessage(Message message) {
ObjectMessage objectMessage = null;
try{
objectMessage = (ObjectMessage) message;
Beers b = (Beers) objectMessage.getObject();
iB.addBeer(b);
}catch(JMSException ex){
ex.printStackTrace();
mdctx.setRollbackOnly();
}
}

}
Re: Learn Java EE With Me by ugwum007(m): 6:38pm On Oct 01, 2016
Console based application client:

- Create a new java project as usual with a main class named Client, add the usual jar libraries and necessary projects (EJB module project, jboss-client.jar, jpa.jar).

this is the source code for the Client class:

//necessary imports
import com.entity.Beers;
import com.remoteinterface.InventoryRemote_JMS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class Client {

BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;


public static void main(String[] args) {

Client cl = new Client();
cl.tasteStatelessEJB();
}

private void tasteStatelessEJB(){
try{
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"wink;
props.put(Context.PROVIDER_URL, "http-remoting://localhost:8050"wink;
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"wink;
props.put(Context.SECURITY_PRINCIPAL, "steinacozguest"wink; //the new created applicationRealm user
props.put(Context.SECURITY_CREDENTIALS, "nkenna007"wink;
props.put("jboss.naming.client.ejb.context", true);

ctx = new InitialContext(props);

}catch(NamingException ex){
ex.printStackTrace();
}

brConsoleReader = new BufferedReader(new InputStreamReader(System.in));

try{

int choice = 1;

Queue queue = (Queue) ctx.lookup("jms/queue/BeerQueue"wink; //lookup for the beer queue
QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory"wink; //lookup for connection factory
QueueConnection connection = factory.createQueueConnection("steinacozguest", "nkenna007"wink;
QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
QueueSender sender = session.createSender(queue);


InventoryRemote_JMS inventoryBean = (InventoryRemote_JMS) ctx.lookup("MDB_BeerInventory/InventoryPersistBean_JMS!com.remoteinterface.InventoryRemote_JMS"wink;
System.out.println("choose right option"wink;
while(choice != 2){
Beers b = new Beers();
String beerName;
String beerPrice;



String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if(choice == 1){
System.out.println("Enter Beer Name: "wink;
beerName = brConsoleReader.readLine();

System.out.println("Enter Beer Price: "wink;
beerPrice = brConsoleReader.readLine();

Beers beer = new Beers();
beer.setBeername(beerName);
beer.setPrice(beerPrice);


//this is where the message is sent
//we didn't call the Persistence Bean this time, rather it was called from the Message Bean
ObjectMessage objectMessage = session.createObjectMessage(beer);
sender.send(objectMessage);


}else if(choice == 2){
break;
}
}

//You already know what this guy does
List<Beers> beersList = inventoryBean.getAllBeers();
System.out.println("Beers entered so far: " + beersList.size());
int i = 0;
for(Beers beer:beersList){
System.out.println("Beer Name: " + "." + beer.getBeername() + " Beer Price: " + beer.getPrice());
}




}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}finally{
try{
if(brConsoleReader != null){
brConsoleReader.close();
}
}catch(IOException ex){
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}

}
Re: Learn Java EE With Me by ugwum007(m): 6:41pm On Oct 01, 2016
I came up with a simple and lite GUI to demonstrate this work for those of us that dislike command line (CLI). It works smoother than CLI.

Re: Learn Java EE With Me by ugwum007(m): 6:48pm On Oct 01, 2016
Use java swing and Create a simple interface like that:

I have to do the first look up in the class constructor so as to improve the speed and get a connection immediately the UI loads.

public Inv_ClientGUI() {
initComponents();
[b] try{
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"wink;
props.put(Context.PROVIDER_URL, "http-remoting://localhost:8050"wink;
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"wink;
props.put(Context.SECURITY_PRINCIPAL, "steinacoz"wink;
props.put(Context.SECURITY_CREDENTIALS, "nkenna007"wink;
props.put("jboss.naming.client.ejb.context", true);

ctx = new InitialContext(props);


inventoryBean = (InventoryRemote) ctx.lookup("Inventory-ejb/InventoryPersistBean!inv.InventoryRemote"wink;

}catch(NamingException ex){
ex.getMessage();
textArea.append("\n" + ex.getMessage() + "\n"wink; //since i don't have the console again, the textArea had to be used to output caught exceptions
}[/b]
}
Re: Learn Java EE With Me by ugwum007(m): 6:52pm On Oct 01, 2016
For the Add button:

place this lines of code in the Add Button (Add_btn) action performed method:

private void add_btnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

[b]
//this is to validate the two textfields and avoid inserting null values into the database
if(name_textField.getText().equals(""wink && price_textField.getText().equals(""wink){
name_textField.setText("Don't leave empty"wink;
price_textField.setText("Don't leave empty"wink;
}else{
try{

InventoryRemote inventoryBean = (InventoryRemote) ctx.lookup("Inventory-ejb/InventoryPersistBean!inv.InventoryRemote"wink;

String beerName, beerPrice;



beerName = name_textField.getText();
beerPrice = price_textField.getText();


Beers beer = new Beers();
beer.setBeername(beerName);
beer.setPrice(beerPrice);
inventoryBean.addBeer(beer);
textArea.append("\n" + "newly Added Beer: " + beerName +" -----Price: N"+ beerPrice + "\n"wink;
name_textField.setText(""wink;
price_textField.setText(""wink;

}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
textArea.append(e.getMessage());
}finally{

}
}
[/b]
}
Re: Learn Java EE With Me by ugwum007(m): 6:58pm On Oct 01, 2016
For the All and Clear button:

place this lines of code in the All Button (all_btn) and Clear button (clr_btn) action performed methods respectively:


private void all_btnActionPerformed(java.awt.event.ActionEvent evt) {

List<Beers> beersList = inventoryBean.getAllBeers();

textArea.setText("total beers in the Inventory: " + beersList.size() + "\n"wink;

for(Beers beers:beersList){

textArea.append("\n" + "Name: " + beers.getBeername()+" Price: N" + beers.getPrice() +"\n"wink; //prints to the text Area
}



}

private void clr_btnActionPerformed(java.awt.event.ActionEvent evt) {

textArea.setText(""wink; //clears the textArea

}
Re: Learn Java EE With Me by ugwum007(m): 7:32pm On Oct 01, 2016
This little GUI source codes have a github repository page: HERE
Re: Learn Java EE With Me by ugwum007(m): 7:34pm On Oct 01, 2016
Next in line is adding a Web Service to this exercise
Re: Learn Java EE With Me by israelboy1(m): 9:18pm On Oct 01, 2016
Thumbs up....I like your spirit....



But...to showing my little concern.

Stop posting your codes here.....xos....you are getting those funny faces....as a result of the smiley codes....to getting them...for instance ) ; will give );



You can post on github ...then put the link here....giving the updates too....or...better still....you can screenshot your new development....and add the link to getting the race code.


Once again....nice job
Re: Learn Java EE With Me by ugwum007(m): 7:04am On Oct 02, 2016
israelboy1:
Thumbs up....I like your spirit....



But...to showing my little concern.

Stop posting your codes here.....xos....you are getting those funny faces....as a result of the smiley codes....to getting them...for instance ) ; will give );



You can post on github ...then put the link here....giving the updates too....or...better still....you can screenshot your new development....and add the link to getting the race code.


Once again....nice job

Thanks, I have opened a github Account.
Re: Learn Java EE With Me by Borwe: 10:01am On Oct 02, 2016
Bro, can you give me a pdf to learn Java EE? I know the basics in Java and have used quite a while now, but I have never touched Java EE, can you assist with tutorial sources? You seem to be pro at this.
Re: Learn Java EE With Me by ugwum007(m): 8:50pm On Oct 02, 2016
Borwe:
Bro, can you give me a pdf to learn Java EE? I know the basics in Java and have used quite a while now, but I have never touched Java EE, can you assist with tutorial sources? You seem to be pro at this.

Bro, am just a learner like you.

ejb tutorial from tutorialspoint.com

Mastering EJB3

[url=http://www.digilife.be/quickreferences/pt/enterprise%20javabeans%20fundamentals.pdf]Enterprise javaBeans fundamentals[/url]
Re: Learn Java EE With Me by steinalb(m): 9:33pm On Oct 02, 2016
To create the web service, we will reuse the inventory-ejb project. open it and add the following lines after the stateless annotation and after the override annotation of getAllbeers() respectively:

@WebService(serviceName = "BeerService"wink
@WebMethod(operationName = "getAllBeers"wink

GITHUB repository for Inventory-ejb project

1 Like

Re: Learn Java EE With Me by steinalb(m): 9:37pm On Oct 02, 2016
- from netbeans create new project wizard, choose Java project; from category, choose Java application
- Create a main class named Inventory_ClientWS inside package com.clientws (don't forget to create this package).

1 Like

Re: Learn Java EE With Me by steinalb(m): 9:48pm On Oct 02, 2016
steinalb:
To create the web service, we will reuse the inventory-ejb project. open it and add the following lines after the stateless annotation and after the override annotation of getAllbeers() respectively:
@WebService(serviceName = "BeerService"wink
@WebMethod(operationName = "getAllBeers"wink
GITHUB repository for Inventory-ejb project

-If you have DEPLOY ON SAVE enabled, the inventory-ejb will automatically deploy if not, clean and build then deploy.
-Watch out for the location of the WSDL file generated by the server from the server console.

-Highlight the new java project (Inventory_ClientWS); click on new > Web Service client
-You can see the location of mine from my server console
-check local file, add the WSDL file location,
-create the package and click on finish.

Re: Learn Java EE With Me by steinalb(m): 9:51pm On Oct 02, 2016
web services are based on the exchange of messages using non-proprietary protocol messages. The messages themselves are not sufficient to define the web service platform. We actually need a list of standard components, including the following:
A language used to define the interfaces provided by a web service in a manner that is not dependent on the platform on which it is running or the programming language used to implement it
A common standard format to exchange messages between web service providers and web service consumers
A registry within which service definitions can be placed. The Web Service Description Language, also known as WSDL,is the de facto standard to provide a description of a web service contract exposed to clients. In particular, a WSDL document describes a web service in terms of the operations that it provides, and the data types that each operation requires as inputs and can return in the form of results.
Re: Learn Java EE With Me by steinalb(m): 9:53pm On Oct 02, 2016
- After creating the creating the file and other things, this is how your project tree will look like.

Re: Learn Java EE With Me by steinalb(m): 10:02pm On Oct 02, 2016
Select Web Service getAllBeers web method as shown in the figure below and drag it to code window of Inventory_ClientWS

Re: Learn Java EE With Me by steinalb(m): 10:06pm On Oct 02, 2016
finally, add the lines of code you see in the main method, Run the project.

NOTE: You can make modifications to the codes to show output in XML or JSON format depending on the format the consumer needs.

Re: Learn Java EE With Me by steinalb(m): 10:09pm On Oct 02, 2016
GITHUB project location for this Web Service demonstration.
Re: Learn Java EE With Me by steinalb(m): 10:15pm On Oct 02, 2016
In the next section, we will implement JavaServer Faces (JSF) which will perform CRUD (Create retrieve update and delete) operations on our database

(1) (2) (3) (4) (Reply)

Cost & Requirements Of Setting Up A Software Productn Company / What's The Best IT Professional Course For Study In Nigeria / Let's Learn Object Oriented PHP!

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 61
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.