master
Caleb Fontenot 2024-04-01 15:32:23 +07:00
parent f6d0920781
commit 346c76633e
29 changed files with 2152 additions and 0 deletions

1
.gitignore vendored

@ -99,3 +99,4 @@
/Semester 3/Assignments/TermProject1_CalebFontenot/target/
/Semester 3/Assignments/params/target/
/Semester 3/Assignments/templatesMatricesSample/target/
/Semester 3/Assignments/StockBrokerAjaxThreads/target/

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scene Scope="Project" version="2">
<Scope Scope="Faces Configuration Only"/>
<Scope Scope="Project"/>
<Scope Scope="All Faces Configurations"/>
</Scene>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>10-web</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>gfv700ee10</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>
<org-netbeans-modules-projectapi.jsf_2e_language>Facelets</org-netbeans-modules-projectapi.jsf_2e_language>
</properties>
</project-shared-configuration>

@ -0,0 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>asdv</groupId>
<artifactId>StockBrokerAjaxThreads</artifactId>
<version>1</version>
<packaging>war</packaging>
<name>StockBrokerAjaxThreads-1</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jakartaee>10.0.0</jakartaee>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>${jakartaee}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>13.0.2</version>
<classifier>jakarta</classifier>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,138 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package asdv.mp1_ajax.pojos;
import java.io.Serializable;
public class Stock implements Serializable
{
private static final long serialVersionUID = 1L;
private String stockId;
private String companyName;
private double priceCurrent;
private double priceClosing;
private long numberOfSharesAvailable;
private long numberOfSharesSold;
public Stock()
{
}
public Stock(String stockId)
{
this.stockId = stockId;
}
public Stock(String stockId, String companyName, double priceCurrent, double priceClosing, long numberOfSharesAvailable, long numberOfSharesSold)
{
this.stockId = stockId;
this.companyName = companyName;
this.priceCurrent = priceCurrent;
this.priceClosing = priceClosing;
this.numberOfSharesAvailable = numberOfSharesAvailable;
this.numberOfSharesSold = numberOfSharesSold;
}
public String getStockId()
{
return stockId;
}
public void setStockId(String stockId)
{
this.stockId = stockId;
}
public String getCompanyName()
{
return companyName;
}
public void setCompanyName(String companyName)
{
this.companyName = companyName;
}
public double getPriceCurrent()
{
return priceCurrent;
}
public void setPriceCurrent(double priceCurrent)
{
this.priceCurrent = priceCurrent;
}
public double getPriceClosing()
{
return priceClosing;
}
public void setPriceClosing(double priceClosing)
{
this.priceClosing = priceClosing;
}
public long getNumberOfSharesAvailable()
{
return numberOfSharesAvailable;
}
public void setNumberOfSharesAvailable(long numberOfSharesAvailable)
{
this.numberOfSharesAvailable = numberOfSharesAvailable;
}
public long getNumberOfSharesSold()
{
return numberOfSharesSold;
}
public void setNumberOfSharesSold(long numberOfSharesSold)
{
this.numberOfSharesSold = numberOfSharesSold;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (stockId != null ? stockId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Stock))
{
return false;
}
Stock other = (Stock) object;
if ((this.stockId == null && other.stockId != null) || (this.stockId != null && !this.stockId.equals(other.stockId)))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "asdv.mp1_ajax.entities.Stock[ stockId=" + stockId + " ]";
}
}

@ -0,0 +1,13 @@
package asdv.stockbrokerajaxthreads;
import jakarta.ws.rs.ApplicationPath;
import jakarta.ws.rs.core.Application;
/**
* Configures Jakarta RESTful Web Services for the application.
* @author Juneau
*/
@ApplicationPath("resources")
public class JakartaRestConfiguration extends Application {
}

@ -0,0 +1,20 @@
package asdv.stockbrokerajaxthreads.resources;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Response;
/**
*
* @author
*/
@Path("jakartaee10")
public class JakartaEE10Resource {
@GET
public Response ping(){
return Response
.ok("ping Jakarta EE")
.build();
}
}

@ -0,0 +1,188 @@
package beans;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import jakarta.faces.context.FacesContext;
import jakarta.faces.event.AbortProcessingException;
import jakarta.faces.event.AjaxBehaviorEvent;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import java.util.Date;
@Named(value = "clientBean")
@ViewScoped
public class ClientBean implements Serializable
{
private boolean viewStcokPrices = false;
private String fromCallerUrlOfParent;
private String fromCallerEmail;
private String name = "";
private String totalValue = "120.00";
private String email = "";
private String emailAgain = "";
private Date date;
private String tickets = "1";
private String price = "120";
private Map<String, Object> ticketAttrs;
public ClientBean()
{
getParametersFromCaller();
this.ticketAttrs = new HashMap<>();
this.ticketAttrs.put("type", "number");
this.ticketAttrs.put("min", "1");
this.ticketAttrs.put("max", "4");
this.ticketAttrs.put("required", "required");
this.ticketAttrs.put("title",
"Enter a number between 1 and 4 inclusive.");
}
private void getParametersFromCaller()
{
//> Get parameters from caller
Map<String, String> m = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
this.fromCallerUrlOfParent = m.get("parent");
this.fromCallerEmail = m.get("email");
}
public boolean isViewStcokPrices()
{
return viewStcokPrices;
}
public void setViewStcokPrices(boolean viewStcokPrices)
{
this.viewStcokPrices = viewStcokPrices;
}
public String getFromCallerStockId()
{
return fromCallerEmail;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getTotalValue()
{
return totalValue;
}
public void setTotalValue(String totalValue)
{
this.totalValue = totalValue;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmailAgain()
{
return emailAgain;
}
public void setEmailAgain(String emailAgain)
{
this.emailAgain = emailAgain;
}
public Date getDate()
{
return date;
}
public void setDate(Date date)
{
this.date = date;
}
public String getTickets()
{
return tickets;
}
public void setTickets(String tickets)
{
this.tickets = tickets;
}
public String getPrice()
{
return price;
}
public void setPrice(String price)
{
this.price = price;
}
public Map<String, Object> getTicketAttrs()
{
return ticketAttrs;
}
public void setTicketAttrs(Map<String, Object> ticketAttrs)
{
this.ticketAttrs = ticketAttrs;
}
public void calculateTotal(AjaxBehaviorEvent event)
throws AbortProcessingException
{
int ticketsNum = 1;
int ticketPrice = 0;
int total;
if (tickets.trim().length() > 0)
{
ticketsNum = Integer.parseInt(tickets);
}
if (price.trim().length() > 0)
{
ticketPrice = Integer.parseInt(price);
}
total = (ticketsNum * ticketPrice);
totalValue = String.valueOf(total) + ".00";
}
public void clear(AjaxBehaviorEvent event)
throws AbortProcessingException
{
name = "";
email = "";
emailAgain = "";
date = null;
price = "120.00";
totalValue = "120.00";
tickets = "1";
}
}

@ -0,0 +1,57 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSF/JSFManagedBean.java to edit this template
*/
package beans;
import asdv.mp1_ajax.pojos.Stock;
import jakarta.inject.Named;
import jakarta.enterprise.context.RequestScoped;
import jakarta.faces.application.ConfigurableNavigationHandler;
import jakarta.faces.context.ExternalContext;
import jakarta.faces.context.FacesContext;
/**
*
* @author asdv5
*/
@Named(value = "login")
@RequestScoped
public class Login
{
private String email;
private String password;
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public void go()
{
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
String page = "client-page";
String params = "&parent=" + "login";
params += "&email=" + this.email;
ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) fc.getApplication().getNavigationHandler();
handler.performNavigation(page + "?faces-redirect=true" + params);
}
}

@ -0,0 +1,82 @@
package beans;
import factory_1_m.OneToMany;
import factory_1_m.OneToManyFactory;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
@Named(value = "oneToManyBean")
@ViewScoped
public class OneToManyBean implements Serializable
{
private String country;
private String city;
private String[] countries =
{
"Greece", "USA"
};
private String[] citiesGreece =
{
"Athens", "Sparta"
};
private String[] citiesUsa =
{
"Lafayette", "New Orleans", "Houston"
};
private OneToMany oneToMany = OneToManyFactory.createOneToMany();
public OneToManyBean()
{
country = this.countries[1];
oneToMany.initializeOne(this.countries);
oneToMany.initializeMany(this.countries[0], citiesGreece);
oneToMany.initializeMany(this.countries[1], citiesUsa);
}
public OneToMany getOneToMany()
{
return oneToMany;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public void handleCountryChange()
{
if (country != null && !country.equals(""))
{
getMany();
}
}
public Collection<String> getMany()
{
if (country != null && !country.equals(""))
{
return this.oneToMany.getMany(country);
}
return Arrays.asList(citiesGreece);
}
}

@ -0,0 +1,179 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSF/JSFManagedBean.java to edit this template
*/
package beans;
import asdv.mp1_ajax.pojos.Stock;
import edu.slcc.ajax.bl.CheckStockPricesThread;
import edu.slcc.ajax.utilities.UtilitiesDatabase;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.event.AbortProcessingException;
import jakarta.faces.event.AjaxBehaviorEvent;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.primefaces.PrimeFaces;
/**
*
* @author a.v. markou
*/
@Named(value = "stockPricesBean")
@ViewScoped
public class StockPricesBean implements Serializable
{
private boolean isThreadRunning = false;
private List<Stock> stocks;
private CheckStockPricesThread stocksThread;
private Thread thread;
private Object parentIDfromJSF;//the id of the element that contains the
// client-page.xhtml
// the ID is: "id_form_container:id_pgStocks"
/**
* Creates a new instance of StockBean
*
* @throws java.lang.Exception
*/
public StockPricesBean()
throws Exception
{
stocksThread = new CheckStockPricesThread();
}
public void parametersFromJSF(Object o)
{
parentIDfromJSF = o;
System.out.println(o + " ------------------parametersFromJSF");
}
@PostConstruct
void init()
{
try
{
thread = new Thread(stocksThread);
thread.start();
isThreadRunning = true;
stocks = this.stocksThread.getStocks();
}
catch (Exception e)
{
System.out.println(e);
UtilitiesDatabase.addMessage(FacesMessage.SEVERITY_FATAL, "Problem occurred with the database.", e.getMessage());
}
}
/**
* The PreDestroy for this bean will not be called until the application
* terminates There is an issue with JSF. You can verify this by looking ta
* the log of Glassfish for the sout "destroy called" WE HAVE TO KILL THE
* THREADS manually with stop method since pre-destroy is not called when
* the this Bean is not viewed anymore.
*
* @ViewScoped: a bean in this scope lives as long as you're interacting
* with the same JSF view in the browser window/tab. It get created upon a
* HTTP request and get destroyed once you postback to a different view. It
* doesn't immediately get destroyed when you leave/close the view by a GET
* request, but it is not accessible the usual way anymore. JSF stores the
* bean in the UIViewRoot#getViewMap() with the managed bean name as key,
* which is in turn stored in the session. You need to return null or void
* from action (listener) methods to keep the bean alive. Use this scope for
* more complex forms which use ajax, data tables and/or several
* rendered/disabled attributes whose state needs to be retained in the
* subsequent requests within the same browser window/tab (view). When you
* want to destroy the bean manually) call the @PreDesroy, use commandLink
* to leave the page.
*/
@PreDestroy
void destroy()
{
System.out.println("destroy called");
if (thread != null)
{
if (thread.isAlive())
{
thread.stop();
isThreadRunning = false;
}
}
}
public List<Stock> getStocks()
{
return stocks;
}
public void setStocks(List<Stock> stocks)
{
this.stocks = stocks;
}
public void mouseClickListener(AjaxBehaviorEvent event)
throws AbortProcessingException
{
System.out.println("+++on click called" + " isThreadRunning=" + isThreadRunning);
if (thread != null)
{
if (!thread.isAlive())
{
if (isThreadRunning == false)
{
isThreadRunning = true;
System.out.println("\tthread.isAlive()=" + thread.isAlive());
System.out.println("\tcreating new thread");
thread = new Thread(stocksThread);
thread.start();
System.out.println("\tthread.start() called");
refresh();
UtilitiesDatabase.addMessage(FacesMessage.SEVERITY_INFO, "on click", "started a thread");
}
}
else//thread is alive, kill it
{
System.out.println("\tthread=" + thread);
System.out.println("\tthread.isAlive()=" + thread.isAlive());
thread.stop();
System.out.println("\tthread.stop() called");
isThreadRunning = false;
UtilitiesDatabase.addMessage(FacesMessage.SEVERITY_INFO, "on click", "destoyed a thread");
}
}
else
{
if (isThreadRunning == false)
{
isThreadRunning = true;
System.out.println("\tthread.isAlive()=" + thread.isAlive());
System.out.println("\tcreating new thread");
thread = new Thread(stocksThread);
thread.start();
System.out.println("\tthread.start() called");
refresh();
UtilitiesDatabase.addMessage(FacesMessage.SEVERITY_INFO, "on click", "started a thread");
}
}
}
public void refresh()
{
System.out.println("refresh!!!()");
if (stocksThread != null)
{
List<String> id = new ArrayList();
id.add(this.parentIDfromJSF.toString());
stocks = stocksThread.getStocks();
PrimeFaces.current().ajax().update(this.parentIDfromJSF.toString());
}
else
{
UtilitiesDatabase.addMessage(FacesMessage.SEVERITY_INFO, "stocksThread is null", "");
}
//FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("f1:id_dataTable1");
}
}

@ -0,0 +1,87 @@
package edu.slcc.ajax.bl;
import asdv.mp1_ajax.pojos.Stock;
import edu.slcc.ajax.utilities.UtilitiesDatabase;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class CheckStockPricesThread
implements Runnable, Serializable
{
static int numberOfThreads = 0;//
long numberOfCallsToDatabase = 0;
StockDB stockDB;
List<Stock> stocks;
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
PreparedStatement ps = null;
Connection con = null;
public CheckStockPricesThread() throws Exception
{
con = new UtilitiesDatabase().connection(databaseName, userName, password, URL2);
// close the resources
stockDB = new StockDB();
System.out.println("CheckStockPrices Runnable created.");
stocks = stockDB.findAll(
con,
databaseName,
userName,
password,
URL2
);
}
public List<Stock> getStocks()
{
return stocks;
}
@Override
public void run()
{
numberOfThreads++;
try
{
while (true)//isInterrupted method Does not clear flag
{
System.out.println("threads = " + numberOfThreads + "\t" + this +": database-calls = " + ++numberOfCallsToDatabase);
stocks = stockDB.findAll(
con,
databaseName,
userName,
password,
URL2
);
Thread.sleep(2000);
}
}
catch (InterruptedException e)
{
System.out.println("---------------------------------Thread interrupt:" + e);
}
catch (Exception e)
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
}
catch (SQLException se)
{
System.out.println(se);
}
}
finally
{
numberOfThreads--;
System.out.println(this + " finally called threads=" + numberOfThreads + ", \ttotal database-calls=" + ++numberOfCallsToDatabase);
numberOfCallsToDatabase = 0;
}
}
}

@ -0,0 +1,28 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
*/
package edu.slcc.ajax.bl;
import java.sql.SQLException;
import java.util.List;
public interface Dao<T>
{
void create(T t)
throws Exception;
void edit(T t)
throws Exception;
void remove(T t)
throws Exception;
T find(Object id)
throws Exception;
List<T> findAll()
throws Exception;
int count() throws Exception;
}

@ -0,0 +1,413 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package edu.slcc.ajax.bl;
import edu.slcc.ajax.utilities.UtilitiesDatabase;
import asdv.mp1_ajax.pojos.Stock;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author asdv5
*/
public class StockDB
implements Dao<Stock>, Serializable
{
@Override
public List<Stock> findAll()
throws Exception
{
List<Stock> tableStocks = new ArrayList<Stock>();
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
PreparedStatement ps = null;
Connection con = null;
try
{
con = new UtilitiesDatabase().connection(
databaseName, userName, password, URL2);
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
String table = "";
ResultSet rs = null;
String sqlStr = "SELECT * FROM stock";
//prepare statement
ps = con.prepareStatement(sqlStr);
//execute
rs = ps.executeQuery();
while (rs.next())
{
String stockId = rs.getString(1);
String companyName = rs.getString(2);
double priceCurrent = rs.getDouble(3);
double priceClosing = rs.getDouble(4);
long numberOfSharesAvailable = rs.getLong(5);
long numberOfSharesSold = rs.getLong(6);
Stock stock = new Stock(stockId, companyName, priceCurrent, priceClosing, numberOfSharesAvailable, numberOfSharesSold);
tableStocks.add(stock);
}
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
// close the resources
if (ps != null)
{
ps.close();
}
}
catch (SQLException sqle)
{
System.out.println(sqle);
sqle.printStackTrace();
throw sqle;
}
}
return tableStocks;
}
public List<Stock> findAll(Connection con,
String databaseName,
String userName,
String password,
String URL2
)
throws Exception
{
List<Stock> tableStocks = new ArrayList<Stock>();
PreparedStatement ps = null;
try
{
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
String table = "";
ResultSet rs = null;
String sqlStr = "SELECT * FROM stock";
//prepare statement
ps = con.prepareStatement(sqlStr);
//execute
rs = ps.executeQuery();
while (rs.next())
{
String stockId = rs.getString(1);
String companyName = rs.getString(2);
double priceCurrent = rs.getDouble(3);
double priceClosing = rs.getDouble(4);
long numberOfSharesAvailable = rs.getLong(5);
long numberOfSharesSold = rs.getLong(6);
Stock stock = new Stock(stockId, companyName, priceCurrent, priceClosing, numberOfSharesAvailable, numberOfSharesSold);
tableStocks.add(stock);
}
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
if (ps != null)
{
ps.close();
}
}
return tableStocks;
}
@Override
public void create(Stock t)
throws Exception
{
int result = 0;
Connection con = null;
try
{
con = new UtilitiesDatabase().connection(
"nyse", "java", "java", "com.mysql.jdbc.Driver");
}
catch (Exception e)
{
System.err.println(e);
throw e;
}
PreparedStatement updateStock = null;
try
{
updateStock = con.prepareStatement(
"INSERT INTO stock (stock_id, company_name, price_current, price_closing, number_of_shares_available, number_of_shares_sold ) "
+ "VALUES ( ?, ?, ? , ? ,? , ?)");
updateStock.setString(1, t.getStockId());
updateStock.setString(2, t.getCompanyName());
updateStock.setDouble(3, t.getPriceCurrent());
updateStock.setDouble(4, t.getPriceClosing());
updateStock.setLong(5, t.getNumberOfSharesAvailable());
updateStock.setLong(6, t.getNumberOfSharesSold());
int updateCount = updateStock.executeUpdate();
result = updateCount;
}
catch (SQLException ex)
{
System.err.println(ex.toString());
throw ex;
}
finally
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
// close the resources
if (updateStock != null)
{
updateStock.close();
}
}
catch (SQLException e)
{
System.err.println(e.toString());
throw e;
}
}
}
@Override
public void edit(Stock t)
throws Exception
{
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
Connection con = null;
PreparedStatement updateSupplier = null;
try
{
con = new UtilitiesDatabase().connection(
databaseName, userName, password, URL2);
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
updateSupplier = null;
updateSupplier = con.prepareStatement(
"UPDATE stock SET stock_id=?, company_name=?, price_current=?, price_closing=?, number_of_shares_available=?, "
+ "number_of_shares_sold=? "
+ "WHERE stock_id=?");
updateSupplier.setString(1, t.getStockId());
updateSupplier.setString(2, t.getCompanyName());
updateSupplier.setDouble(3, t.getPriceCurrent());
updateSupplier.setDouble(4, t.getPriceClosing());
updateSupplier.setLong(5, t.getNumberOfSharesAvailable());
updateSupplier.setLong(6, t.getNumberOfSharesSold());
updateSupplier.setString(7, t.getStockId());
int result = updateSupplier.executeUpdate();
}
catch (SQLException ex)
{
System.err.println(ex.toString());
throw ex;
}
finally
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
// close the resources
if (updateSupplier != null)
{
updateSupplier.close();
}
}
catch (SQLException sqlee)
{
sqlee.printStackTrace();
throw sqlee;
}
}
}
@Override
public void remove(Stock t)
throws Exception
{
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
Connection con = null;
PreparedStatement ps = null;
try
{
con = new UtilitiesDatabase().connection(
databaseName, userName, password, URL2);
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
int rowsAffected = -1;
String query = "DELETE FROM stock WHERE stock_id=? ";
ps = con.prepareStatement(query);
ps.setString(1, t.getStockId());
rowsAffected = ps.executeUpdate();
}
catch (Exception ex)
{
System.err.println(ex.toString());
}
finally
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
// close the resources
if (ps != null)
{
ps.close();
}
}
catch (SQLException sqlee)
{
sqlee.printStackTrace();
}
}
}
@Override
public Stock find(Object id)
throws Exception
{
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
PreparedStatement ps = null;
Connection con = null;
try
{
con = new UtilitiesDatabase().connection(
databaseName, userName, password, URL2);
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
String table = "";
ResultSet rs = null;
String sqlStr = "SELECT * FROM stock WHERE stock_id=? ";
//prepare statement
ps = con.prepareStatement(sqlStr);
ps.setString(1, (String) id);
//execute
rs = ps.executeQuery();
if (rs.next())
{
String stockId = rs.getString(1);
String companyName = rs.getString(2);
double priceCurrent = rs.getDouble(3);
double priceClosing = rs.getDouble(4);
long numberOfSharesAvailable = rs.getLong(5);
long numberOfSharesSold = rs.getLong(6);
Stock stock = new Stock(stockId, companyName, priceCurrent, priceClosing, numberOfSharesAvailable, numberOfSharesSold);
return stock;
}
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
new UtilitiesDatabase().closeDatabaseConnection(con);
// close the resources
if (ps != null)
{
ps.close();
}
}
catch (SQLException sqle)
{
System.out.println(sqle);
sqle.printStackTrace();
throw sqle;
}
}
return null;
}
@Override
public int count()
throws Exception
{
String databaseName = "nyse";
String userName = "java";
String password = "java";
String URL2 = "com.mysql.jdbc.Driver";
PreparedStatement ps = null;
Connection con = null;
int rowCount = -1;
try
{
con = new UtilitiesDatabase().connection(
databaseName, userName, password, URL2);
if (con == null)
{
throw new RuntimeException("cannot connect to database");
}
ResultSet rs = null;
String sqlStr = "SELECT count(*) " + " FROM " + "stock";
ps = con.prepareStatement(sqlStr);
rs = ps.executeQuery(sqlStr);
if (rs.next() == true)
{
rowCount = rs.getInt(1);
}
}
catch (SQLException ex)
{
Logger.getLogger(StockDB.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
throw ex;
}
finally
{
try
{
if (ps != null)
{
ps.close();
}
}
catch (SQLException sqle)
{
Logger.getLogger(StockDB.class.getName()).log(Level.WARNING, null, sqle);
sqle.printStackTrace();
throw sqle;
}
}
return rowCount;
}
}

@ -0,0 +1,111 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package edu.slcc.ajax.utilities;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
public class UtilitiesDatabase
{
public Connection connection(
String databaseName,
String userName,
String password,
String URL2
) throws SQLException, InstantiationException,
IllegalAccessException, ClassNotFoundException
{
Connection con;
try
{// Load Sun's jdbc driver
Class.forName(URL2).newInstance();
System.out.println("JDBC Driver loaded!");
}
catch (Exception e) // driver not found
{
System.err.println("Unable to load database driver");
System.err.println("Details : " + e);
throw e;
}
String ip = "localhost"; //internet connection
String url = "jdbc:mysql://" + ip + ":3306/" + databaseName + "?allowPublicKeyRetrieval=true&useSSL=false";
try
{
con = DriverManager.getConnection(url, userName, password);
con.setReadOnly(false);
}
catch (Exception e)
{
System.err.println(e.toString());
throw e;
}
System.out.println("connection successfull");
return con;
}
public void closeDatabaseConnection(Connection con)
throws SQLException
{
try
{
if (con != null)
{
con.close();
}
}
catch (SQLException e)
{
System.out.println(e);
e.printStackTrace();
throw e;
}
}
public static java.sql.Date stringDateToSqlDate(String sDate)
{
java.util.Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try
{
date = sdf.parse(sDate);
}
catch (ParseException e)
{
e.printStackTrace();
}
return new java.sql.Date(date.getTime());
}
public static java.util.Date stringDateToJavaUtilitiesDate(String sDate)
{
java.sql.Date sqldate = stringDateToSqlDate(sDate);
return new java.util.Date(sqldate.getTime());
}
public static void addMessage(FacesMessage.Severity severity, String summary, String detail)
{
FacesMessage msg = new FacesMessage(severity, summary, detail);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public static void clearAllMessages()
{
FacesContext context = FacesContext.getCurrentInstance();
Iterator<FacesMessage> it = context.getMessages();
while (it.hasNext())
{
it.next();
it.remove();
}
}
}

@ -0,0 +1,68 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package factory_1_m;
import java.util.Collection;
import java.util.Set;
/**
*
* @author asdv5
* @param <One>
* @param <Many>
*/
public interface OneToMany<One, Many>
{
/**
* Initialization of Ones. The method should be used first before any other
* methods
*
* @param one - the ones ( i.e, countries, or SelectItem or any Object) to
* use for initialization
* @return true if the initialization succeeded by using the method once,
* false when the method is used more than once.
*/
boolean initializeOne(One... one);
/**
* Initialization of the many for a given one. The method can be used
* multiple times after the method initializeOne has succeeded.
*
* @param one - the one that has the many
* @param many - the many which belong to th eone
* @throws IllegalArgumentException when the one does not exist (i.e. user's
* typing error for the name of one) or when the initialization of the one
* has not occurred.
*
*/
void initializeMany(One one, Many... many)
throws IllegalArgumentException;
/**
* Gets the many of a specific one.
*
* @param one the one to get its many
* @return the many of the parameter one or null if the one does not exist.
*/
Collection<Many> getMany(One one);
/**
* Given a value of the many it gets the one that the many belongs to.
*
* @param many one of the values of the many
* @return the one
*/
One getOne(Many many);
/**
* Gets a set with all the ones
*
* @return the set of ones.
*/
Set<One> getAllOnes();
}

@ -0,0 +1,204 @@
package factory_1_m;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class OneToManyFactory
{
/**
* Creates an object of type OneToMany
*
* @param <One> a generic parameter can be any object that denotes a One.
* @param <Many> a generic parameter can be any object that denotes a city
* that belongs to the one generic type.
* @return a OneCity object.
*/
public static <One, Many> //generic types to be used in the method
OneToMany<One, Many> //rturn type
createOneToMany()
{
return new OneToMany<One, Many>()
{
private Map<Object, Object> oneToMany = new HashMap();
boolean oneInitialized = false;
boolean manyInitialized = false;
@Override
public boolean initializeOne(One... one)
{
if (oneInitialized == false && manyInitialized == false)
{
for (int i = 0; i < one.length; ++i)
{
oneToMany.put(one[i], new Boolean(true));
}
oneInitialized = true;
return true;
}
return false;
}
@Override
public void initializeMany(One one, Many... many)
throws IllegalArgumentException
{
if (oneToMany.get(one) == null)//if the key of the one is null
{//the method initializekey has not been used
throw new IllegalArgumentException(one + " is not valid");
}
oneToMany.put(one, new ArrayList<Many>(Arrays.asList(many)));
manyInitialized = true;
}
@Override
public Collection<Many> getMany(One one)
throws IllegalArgumentException
{
if (oneInitialized == true && manyInitialized == true)
{
if (oneToMany.get(one) == null)
{
throw new IllegalArgumentException(one + " is not a valid One");
}
Collection c1 = (Collection) oneToMany.get(one);
return c1;
}
return null;
}
@Override
public One getOne(Many many)
{
Set< Entry<Object, Object>> set = oneToMany.entrySet();
for (Map.Entry<Object, Object> entry : oneToMany.entrySet())
{
One key = (One) entry.getKey();
Collection<Many> value = (Collection<Many>) oneToMany.get(key);
if (value.contains(many))
{
return key;
}
}
return null;
}
@Override
public Set<One> getAllOnes()
{
return (Set<One>) oneToMany.keySet();
}
};
}
public static void main(String[] args)
{
OneToMany cc = OneToManyFactory.createOneToMany();
try
{
cc.initializeMany("France", "Paris");
}
catch (Exception e)
{
System.err.println(e);
}
boolean b1 = cc.initializeOne("USA", "Greece");
System.out.println(b1);
boolean b2 = cc.initializeOne("USA", "Greece");
System.out.println(b2);
cc.initializeMany("USA", "Lafayette", "New Orleans");
cc.initializeMany("Greece", "Athens", "Sparta");
Collection<String> cities1 = cc.getMany("USA");
System.out.println(cities1);
Collection<String> cities2 = cc.getMany("Greece");
System.out.println(cities2);
System.out.println(cc.getOne("Athens"));
System.out.println(cc.getOne("Lafayette"));
System.out.println(cc.getOne("France"));
try
{
System.out.println(cc.getMany("Germany"));
}
catch (Exception e)
{
System.err.println(e);
}
System.out.println(cc.getAllOnes());
System.out.println("--------------------------------------");
OneToMany supplierParts = OneToManyFactory.createOneToMany();
Supplier s1 = new Supplier("s1");
Supplier s2 = new Supplier("s2");
supplierParts.initializeOne(s1, s2);
Part p1 = new Part("p1");
Part p2 = new Part("p2");
Part p3 = new Part("p3");
Part p4 = new Part("p4");
supplierParts.initializeMany(s1, p1,p2);
supplierParts.initializeMany(s2, p3,p4);
System.out.println( supplierParts.getMany(s1));
System.out.println( supplierParts.getMany(s2));
System.out.println( supplierParts.getOne(p1) );
}
}
class Supplier
{
private String name;
public Supplier(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Override
public String toString()
{
return "Supplier{" + "name=" + name + '}';
}
}
class Part
{
private String name;
public Part(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
@Override
public String toString()
{
return "Part{" + "name=" + name + '}';
}
}

@ -0,0 +1,39 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package factory_1_m;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
*
* @author asdv5
*/
public class TestMap
{
public static void main(String[] args)
{
HashMap<String, ArrayList<String>> map = new HashMap();
ArrayList l1 = new ArrayList<String>();
l1.add("p1");
l1.add("p2");
map.put("e1", l1);
ArrayList l2 = new ArrayList<String>();
l2.add("p2");
l2.add("p3");
map.put("e2", l2);
System.out.println(map);
Collection<ArrayList<String>> c = map.values();
System.out.println(c);
for (ArrayList<String> a : c )
a.remove("p2");
System.out.println(c);
System.out.println(map);
}
}

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="3.0" xmlns="https://jakarta.ee/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
<!-- Define Persistence Unit -->
<persistence-unit name="my_persistence_unit">
</persistence-unit>
</persistence>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_4_0.xsd"
bean-discovery-mode="all">
</beans>

@ -0,0 +1,16 @@
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="4.0"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-facesconfig_4_0.xsd">
<!-- We can start the bean automatically -->
<!--
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>beans.CheckStockPricesBean</managed-bean-class>
<managed-bean-scope>application</managed-bean-scope></managed-bean>
-->
</faces-config>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v. 2.0, which is available at
http://www.eclipse.org/legal/epl-2.0.
This Source Code may also be made available under the following Secondary
Licenses when the conditions for such availability set forth in the
Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
version 2 with the GNU Classpath Exception, which is available at
https://www.gnu.org/software/classpath/license.html.
SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
-->
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class' java code.</description>
</property>
</jsp-config>
</glassfish-web-app>

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="6.0" xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd">
<context-param>
<param-name>jakarta.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>jakarta.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<mime-mapping>
<extension>otf</extension>
<mime-type>font/opentype</mime-type>
</mime-mapping>
<mime-mapping>
<extension>ttf</extension>
<mime-type>application/x-font-ttf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>woff</extension>
<mime-type>application/x-font-woff</mime-type>
</mime-mapping>
<mime-mapping>
<extension>woff2</extension>
<mime-type>application/x-font-woff2</mime-type>
</mime-mapping>
<mime-mapping>
<extension>svg</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>eot</extension>
<mime-type>application/vnd.ms-fontobject</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>faces/login.xhtml</welcome-file>
</welcome-file-list>
</web-app>

@ -0,0 +1,97 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f5="http://xmlns.jcp.org/jsf/passthrough"
xmlns:ui="jakarta.faces.facelets"
xmlns:f="jakarta.faces.core">
<h:head>
<title>Client</title>
</h:head>
<h:body>
<h:form id="f1">
<p:growl id="id_growl_messages_client"
globalOnly="true"
showDetail="true" redisplay="false"/>
<h1> User Name: #{clientBean.fromCallerStockId} </h1>
<h:panelGrid columns="1" cellpadding="10" >
<p:column>
<p:outputLabel value="Your Country: " />
<p:selectOneMenu
id="countries" value="#{oneToManyBean.country}">
<f:selectItems value="#{oneToManyBean.oneToMany.getAllOnes()}" />
<p:ajax listener= "#{oneToManyBean.handleCountryChange}"
event="change" update="cities" process="@this"/>
</p:selectOneMenu>
<p:outputLabel value="Your City: " />
<p:selectOneMenu id="cities" value="#{oneToManyBean.city}">
<f:selectItems value="#{oneToManyBean.getMany()}" />
</p:selectOneMenu>
</p:column>
<p:column>
<p:calendar id="date"
f5:placeholder="Date to buy/sell stocks"
readonlyInput="true"
value="#{clientBean.date}"
required="required"
title="Enter or choose a date."/>
</p:column>
<p:column>
<p:outputLabel value="Number of Stocks: " />
<h:inputText id="tickets" value="#{clientBean.tickets}">
<f:passThroughAttributes value="#{clientBean.ticketAttrs}"/>
<p:ajax event="change" update="total"
listener="#{clientBean.calculateTotal}"/>
</h:inputText>
<p:outputLabel value="Stock price: " />
<p:inputText id="price"
value="#{clientBean.price}"
p:step="20" p:required="required" >
<p:ajax event="change" update="total" process="@this"
listener="#{clientBean.calculateTotal}"/>
</p:inputText>
<br/>
<p:outputLabel value="Estimated total: " />
<p:outputLabel id="total"
value="#{clientBean.totalValue}"
>
</p:outputLabel>
</p:column>
</h:panelGrid>
<p:commandButton value="Clear"
action="confirmation">
<p:ajax update="@all" listener="#{clientBean.clear}"/>
</p:commandButton>
<br/>
<p:selectBooleanCheckbox itemLabel="See Stock Prices"
value="#{clientBean.viewStcokPrices}" >
<p:ajax
event="change" process="@this"
update="id_form_container:id_pgStocks"
/>
</p:selectBooleanCheckbox>
</h:form >
<h:form id="id_form_container">
<p:panelGrid id="id_pgStocks" columns="1" >
<p:column rendered="#{clientBean.viewStcokPrices}" >
<ui:include src="stock-prices.xhtml" >
<ui:param name="id_parent"
value="id_form_container:id_pgStocks"/>
</ui:include >
</p:column>
</p:panelGrid>
<p:commandLink value="destroy the view-scoped clientBean and the included view-scoped bean " action="client-page"/>
</h:form>
</h:body>
</html>

@ -0,0 +1,35 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f5="http://xmlns.jcp.org/jsf/passthrough"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title >Login</title>
</h:head>
<h:body>
<h:form style=" margin-top:10%; display: block;
margin-left: auto; margin-right: auto;
width: fit-content" >
<h3 style="color: grey"> Login </h3>
<p:panelGrid columns="1" style=" border-top: solid lightgray; border-bottom: solid lightgray">
<p:column style=" background:#fffffa" >
<p:inputText required="true" style="margin-right: 20px" value="#{login.email}" f5:type="email" f5:placeholder="E-mail"/>
<p:password required="true" value="#{login.password}" f5:placeholder="Password"
/>
</p:column>
<p:column style=" background:#fffffa" >
<p:commandButton style=" display: block;
margin-left: auto;
border-radius: 30%;
margin-right: auto;border: 3px solid lightblue;"
ajax="false" value="Login" action="#{login.go}" />
</p:column>
</p:panelGrid>
</h:form>
</h:body>
</html>

@ -0,0 +1,79 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:f5="http://xmlns.jcp.org/jsf/passthrough"
xmlns:ui="jakarta.faces.facelets">
<h:head>
<title>MP1 Ajax</title>
<h:outputStylesheet library="css" name="styles.css"/>
</h:head>
<h:body>
<ui:composition>
${stockPricesBean.parametersFromJSF(id_parent)}
<h:form id="id_f11" >
<p:growl id="id_growl_messages"
globalOnly="true"
showDetail="true" redisplay="false"/>
<p:dataTable id= "id_d11" value ="#{stockPricesBean.stocks }"
style="width: 100%; "
var="stock"
scrollable="true"
paginator="true"
paginatorPosition="bottom"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {CurrentPageReport}"
currentPageReportTemplate="{startRecord} to {endRecord} of #{stockPricesBean.getStocks().size() } "
rows="2"
resizableColumns="true"
rowHover ="true"
draggableRows="true"
draggableColumns="true"
rowKey="#{stock.stockId}"
selectionMode="single"
selection="#{stock}"
>
<p:column headerText="Stock ID"
sortBy="#{stock.stockId}" >
<p:outputLabel title= "Stock ID" value="#{stock.stockId}" />
</p:column >
<p:column id="id_stockName" headerText="Stock Name"
sortBy="#{stock.companyName}" >
<p:outputLabel title= "Stock Name" value="#{stock.companyName}" />
</p:column >
<p:column id="id_col" headerText="Current Price" >
<p:outputLabel id="id_l11" title= "Current Price" value="#{stock.priceCurrent}" />
</p:column >
<p:column id="id_closingPriceColumn" headerText="Closing Price"
sortBy="#{stock.priceClosing}" >
<p:outputLabel id="id_closingPriceLabel" title= "Closing Price" value="#{stock.priceClosing}" />
</p:column >
<p:column id="id_sharesAvailable"
headerText="Shares Availlable"
sortBy="#{stock.numberOfSharesAvailable}" >
<p:outputLabel title= "Shares Available" value="#{stock.numberOfSharesAvailable}" />
</p:column >
<p:column id="id_sharesSold"
headerText="Shares Sold"
sortBy="#{stock.numberOfSharesSold}" >
<p:outputLabel title= "Shares Sold" value="#{stock.numberOfSharesSold}" />
</p:column >
</p:dataTable>
<p:draggable for="id_d11" helper="clone" opacity="0.5"/>
<p:ajax event="click" update="id_growl_messages"
listener="#{stockPricesBean.mouseClickListener}" />
</h:form>
</ui:composition>
</h:body>
</html>

@ -0,0 +1,11 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="jakarta.faces.html">
<h:head>
<title>test</title>
</h:head>
<h:body>
test
</h:body>
</html>

@ -0,0 +1,109 @@
-- phpMyAdmin SQL Dump
-- version 5.2.0
-- https://www.phpmyadmin.net/
--
-- Host: localhost:8889
-- Generation Time: Mar 25, 2024 at 02:28 PM
-- Server version: 5.7.39
-- PHP Version: 7.4.33
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `nyse`
--
-- --------------------------------------------------------
--
-- Table structure for table `stock`
--
CREATE TABLE `stock` (
`stock_id` varchar(4) NOT NULL,
`company_name` varchar(100) NOT NULL,
`price_current` double NOT NULL,
`price_closing` double NOT NULL,
`number_of_shares_available` bigint(20) NOT NULL,
`number_of_shares_sold` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `stock`
--
INSERT INTO `stock` (`stock_id`, `company_name`, `price_current`, `price_closing`, `number_of_shares_available`, `number_of_shares_sold`) VALUES
('AMZN', 'Amazon Inc.', 6, 188, 7779754, 1111),
('GOO', 'Google Inc.', 986, 399, 1000000, 1000000),
('PLCE', 'Children\'s Place, Inc.', 14.515, 13.515, 10000000, 5000000),
('TSLA', 'Tesla Inc.', 191.73, 202.98, 4000000, 1000000);
-- --------------------------------------------------------
--
-- Table structure for table `stock_holder`
--
CREATE TABLE `stock_holder` (
`stock_holder_id` int(11) NOT NULL,
`name` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `transactions`
--
CREATE TABLE `transactions` (
`stock_holder_id` int(11) NOT NULL,
`stock_id` varchar(4) NOT NULL,
`qty` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `stock`
--
ALTER TABLE `stock`
ADD PRIMARY KEY (`stock_id`);
--
-- Indexes for table `stock_holder`
--
ALTER TABLE `stock_holder`
ADD PRIMARY KEY (`stock_holder_id`);
--
-- Indexes for table `transactions`
--
ALTER TABLE `transactions`
ADD PRIMARY KEY (`stock_holder_id`,`stock_id`),
ADD KEY `stock_id` (`stock_id`);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `transactions`
--
ALTER TABLE `transactions`
ADD CONSTRAINT `transactions_ibfk_1` FOREIGN KEY (`stock_id`) REFERENCES `stock` (`stock_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `transactions_ibfk_2` FOREIGN KEY (`stock_holder_id`) REFERENCES `stock_holder` (`stock_holder_id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;