Computer Science and Computer Engineering treats:621437

Question:

(So you may ask: why do we have the constructor in class Recipe? This will be left for you to figure
out.)
The second class, RecipeDSC, is the data source controller. The Data Source Controller (DSC) is the
class that handles all of the add/remove/update operations between your running program and the
database. A skeleton of this class is provided.
The third and the fourth classes, RecipeSystem and RecipeStageMaker, provide the graphical user
interface for the users to interact with the system. These classes are to be implemented in JavaFX. A
skeleton for each of these classes is provided.
An SQL script is provided to create the tables, and seeds the database with some sample data
Task 1
Implement the RecipeDSC class, with
The ability to get the username and password from the user (i.e., not hard coded).
Be able to connect to the database and retrieve and display the sample data.
A skeleton of the class is provided, which indicates the methods that you are required to implement.
Task 2
Implement the RecipeMain class. When the system is started, a screen similar to the one shown in
Figure 1 is displayed.
Searching.
At the top of the screen, we can enter text that is used for searching. If we check “Any
Field”, the table view displays recipes that have any field containing the search string (this
constitutes a “match”). If we check “Ingredients” button, the table view displays recipes that have
the ingredients containing the search string. And if we check “Recipe Name” button, the table view
displays items that have the name containing the search string.
Table View.
The table view displays the recipes in the collection, one recipe per row. The table view
does not display the steps of the recipes, or the quantities of each ingredient. The steps will be
displayed when the user select a recipe and clicks the “View/Update Selected Recipe” button. The
ingredients field is displayed in the text-wrap mode. An example of the ingredients is shown below:
ALMOND MILK, QUINOA, BANANA, RASPBEERRIES
The string shows four ingredients. The names of the ingredients are in capital. The ingredients are
separated by commas.
Buttons for all key functionality
. This is the “View/Update Selected Recipe” button, “Add New
Recipe” button, and “Delete Selected Recipe” Button.
Task 3
Implement the RecipeStageMaker class and link it to the three buttons on the primary screen.
“View/Update Selected
Recipe” button.
When we click on the “View/Update Selected Recipe” button, the program calls method
showViewRecipeStage of the RecipeStageMaker class, which should display a screen similar to the
one shown in Figure 2.
The program should display this screen some distance to the right and below that of the main
screen.
The stage displays all the details of the selected recipe for the user to view. The user can also update
the details of the displayed recipe. To do so, the user changes the details displayed in the text fields
and text area, except the id. The user can choose to update the recipe (by clicking on the “UPDATE
Recipe” button, or cancel the operation (by clicking on the “EXIT/CANCEL” button).

Answer:

/**

* Created by krogers on 18/08/2017.

*/

 

 

public class Ingredient {

 

private int ID;

private String name;

private double quantity;

private String unitsAndStyle;

private boolean deleted = false;

 

public Ingredient()

{

this.ID = -1;

this.name = “no name”;

this.quantity = 0;

this.unitsAndStyle = “”;

this.deleted = false;

}

 

public Ingredient(int ID, String name, double quantity, String unitsAndStyle)

{

this.ID = ID;

this.name = name;

this.quantity = quantity;

this.unitsAndStyle = unitsAndStyle;

this.deleted = false;

}

 

public boolean isDeleted() {

return deleted;

}

public void setID(int ID) {

this.ID = ID;

}

public void setName(String name) {

this.name = name;

}

public void setQuantity(double quantity) {

this.quantity = quantity;

}

public void setUnitsAndStyle(String unitsAndStyle) {

this.unitsAndStyle = unitsAndStyle;

}

 

public void setDeleted(boolean deleted) {

this.deleted = deleted;

}

public int getID() {

return ID;

}

public String getName() {

return name;

}

public double getQuantity() {

return quantity;

}

public String getUnitsAndStyle() {

return unitsAndStyle;

}

 

@Override

public String toString() {

return quantity + ” ” + unitsAndStyle + ” ” + name;

}

public String toString(String indent) {

return indent + quantity + ” ” + unitsAndStyle + ” ” + name;

}

}

 

 

import java.util.ArrayList;

import java.util.List;

 

public class Recipe

{

private int ID;

private String name;

private int serves;

private List<Ingredient> ingredients;

private String steps;

private String remarks;

 

public Recipe(int ID, String name, int serves, String steps, String remarks)

{

this.ID = ID;

this.name = name;

this.serves = serves;

this.steps = steps;

this.remarks = remarks;

this.ingredients = new ArrayList<>();

}

public Recipe(String name, int serves, String steps, String remarks)

{

this.ID = -1;

this.name = name;

this.serves = serves;

this.steps = steps;

this.remarks = remarks;

this.ingredients = new ArrayList<>();

}

 

public Ingredient getIngredientByID(int ingID)

{

for (Ingredient I: ingredients)

{

if (I.getID() == ingID)

{

return  I;

}

}

return null;

}

 

public int getID()

{

return ID;

}

 

public String getName()

{

return name;

}

 

public void setName(String name)

{

this.name = name;

}

 

public int getServes()

{

return serves;

}

 

public void setServes(int serves)

{

this.serves = serves;

}

 

public List<Ingredient> getIngredients() {

return ingredients;

}

 

public void setIngredients(List<Ingredient> ingredients) {

this.ingredients = ingredients;

}

 

public String getSteps()

{

return steps;

}

 

public void setSteps(String steps)

{

this.steps = steps;

}

 

public String getRemarks()

{

return remarks;

}

 

public void setRemarks(String remarks)

{

this.remarks = remarks;

}

 

public void addIngredient(Ingredient ingredient)

{

this.ingredients.add(ingredient);

}

 

public void update(String name, int serves,

String steps, String remarks)

{

this.name = name;

this.serves = serves;

this.steps = steps;

this.remarks = remarks;

}

 

@Override

public String toString()

{

return “\nRecipe{\n\t” +

“ID: ” + ID + “\n\t” +

“name: ” + name + “\n\t” +

“serves: ” + serves + “\n\t” +

“ingredients: ” + ingredients + “\n\t” +

“steps: ” +  steps  + “\n\t” +

“remarks = ” + remarks + “}\n”;

}

 

@Override

public boolean equals(Object obj)

{

return

obj != null &&

obj instanceof Recipe &&

((Recipe) obj).getID() == this.ID;

}

}

 

 

 

import javafx.scene.control.TextInputDialog;

import javafx.stage.Modality;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.sql.Statement;

import java.sql.*;

 

import java.util.ArrayList;

import java.util.List;

import java.util.Optional;

 

public class RecipeDSC

{

private  Connection connection;

private  Statement statement;

private  PreparedStatement preparedStatement;

private String username = null;

private String password = null;

private String url = null;

 

private boolean useAlertForInput = true;

 

public String getInfoFromUser( String userInstructions)

{

if (useAlertForInput) {

final TextInputDialog inputDlg = new TextInputDialog(“”);

//inputDlg.initOwner(parent);

inputDlg.setTitle(“information Required”);

inputDlg.setContentText(userInstructions);

inputDlg.setHeaderText(null);

inputDlg.initModality(Modality.APPLICATION_MODAL);

Optional<String> userResponce = inputDlg.showAndWait();

while (!userResponce.isPresent())

userResponce = inputDlg.showAndWait();

return userResponce.get();

 

}

try {

System.out.println(userInstructions);

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

return br.readLine();

}

catch (IOException e)

{

System.out.println(e);

}

return “”;

}

 

public  void connect() throws SQLException

{

// String url = “jdbc:mysql://latcs7.cs.latrobe.edu.au:3306/username”;

// String user = “<student username>”;

try{

if  (url == null) {

String userResponce = getInfoFromUser( “Please enter your database url”);

if (userResponce.equals(“”)) {

System.out.println(” You have not entered any URL”);

userResponce = getInfoFromUser( “Please enter your database url”);

}

else {

url = userResponce;

}

}

if (username == null) {

username = getInfoFromUser( “Please enter your database username for ” + url);

}

if (password == null) {

password = getInfoFromUser( “Please enter your database password for user: ” + username);

}

connection = DriverManager.getConnection(url, username, password);

statement = connection.createStatement();

System.out.println(“Connection established”);

}catch (Exception e){

System.out.println(“Connection error \n”+ e);

}

}

 

public  void disconnect() throws SQLException

{

if (preparedStatement != null) preparedStatement.close();

if (statement != null) statement.close();

if (connection != null) connection.close();

}

 

 

/*

* TODO:        This method should find a Recipe with the given id.

* @param       id The id of the Recipe to be found.

* @return       The Recipe with the given id if it exists. Otherwise return null.

* @throws     SQLException

*/

public Recipe find(int id) throws SQLException

{

 

Recipe recipe=new Recipe(null,0,null,null);

try{

 

ResultSet rs = statement.executeQuery(“SELECT * FROM recipes WHERE ID='”+id+”‘”);

//loop

while(rs.next()){

recipe.setName(rs.getString(“name”));

recipe.setRemarks(rs.getString(“remarks”));

recipe.setServes(Integer.parseInt(rs.getString(“serves”)));

recipe.setSteps(rs.getString(“steps”));

}

return recipe;

}catch(Exception e){

System.out.println(e);

return null;

}

}

 

/*

* TODO:        This method should count the total number of Recipes in the database

* @return       An int representing the number of Recipes

* @throws     SQLException

*/

public int count() throws SQLException

{

 

int count=0;

try{

 

ResultSet rs = statement.executeQuery(“SELECT * FROM recipes”);

//loop

while(rs.next()){

 

count++;

}

return count;

}catch(Exception e){

System.out.println(e);

return 0;

}

}

 

 

/**

* TODO:        This method should obtain and return  the list of all Recipes

*                                 from the database

* @return       The list of all Recipes stored in the database

* @throws     SQLException

*/

public List<Recipe> findAll() throws SQLException

{

List rList=new ArrayList<Recipe>();

Recipe recipe=new Recipe(null,0,null,null);

try{

 

ResultSet rs = statement.executeQuery(“SELECT * FROM recipes”);

//loop

while(rs.next()){

recipe.setName(rs.getString(“name”));

recipe.setRemarks(rs.getString(“remarks”));

recipe.setServes(Integer.parseInt(rs.getString(“serves”)));

 

//recipe.setIngredients(findAllIngredients(rs.getInt(“ID”)));

recipe.setSteps(rs.getString(“steps”));

rList.add(recipe);

 

}

return rList;

}catch(Exception e){

System.out.println(e);

return null;

}

}

 

/**

* TODO:        This method should obtain and return  the list of all Ingredients for a given recipe ID

*                                 from the database

* @return       The list of Ingredients

* @throws     SQLException

*/

 

public List<Ingredient> findAllIngredients(int recipeID) throws SQLException

{

List rList=new ArrayList<Ingredient>();

Ingredient ingredient=new Ingredient(0,null,0,null);

try{

Statement statement2 = connection.createStatement();

ResultSet rs = statement2.executeQuery(“SELECT * FROM recipeingredients WHERE recipeID='”+recipeID+”‘”);

//loop

while(rs.next()){

ingredient.setID(rs.getInt(“ID”));

ingredient.setName(rs.getString(“name”));

ingredient.setQuantity(rs.getDouble(“quantity”));

ingredient.setUnitsAndStyle(rs.getString(“unitsAndStyle”));

rList.add(ingredient);

 

}

return rList;

}catch(Exception e){

System.out.println(e);

return null;

}

}

 

 

/*

* TODO:        This method should try to add a new Ingredient with the details

*                                 provided by the parameters

*         @param           All the details of the recipe to be added (except the id)

*         @return           The id of the recipe (which is generated by the database)

* @throws     SQLException

*/

public int addIngredient(int recipeID, String name, double quantity, String unitsAndStyle) throws SQLException {

try

{

String sql=”INSERT INTO recipeIngredients (recipeID,name,quantity,unitsAndStyle) VALUES (‘”+recipeID+”‘,'”+name+”‘,'”+quantity+”‘,'”+unitsAndStyle+”‘)”;

statement.execute(sql);

ResultSet rs = statement.executeQuery(“SELECT ID FROM recipeIngredients ORDER BY ID DESC LIMIT 1”);

int id=0;

//loop

while(rs.next()){

id=rs.getInt(“ID”);

}

return id;

}

catch(Exception e){

System.out.println(e);

return 0;

}

}

public int addIngredient(Ingredient ingredient) throws SQLException {

// Should simply call the previous method

return addIngredient(ingredient.getID(),ingredient.getName(),ingredient.getQuantity(),ingredient.getUnitsAndStyle());

}

 

/*

* TODO:        This method should try to updated an existing Recipe with the details

*                                 provided by the parameters

*         @param           All the details of the recipe to be added (except the id)

*  @throws    SQLException

*/

public int updateIngredient(int ingredientID, String name, double quantity, String unitsAndStyle) throws SQLException {

try

{

String sql=”UPDATE INTO recipeIngredients SET name='”+name+”‘,quantity'”+quantity+”‘,unitsAndStyle='”+unitsAndStyle+”‘ WHERE ID='”+ingredientID+”‘”;

statement.execute(sql);

return 1; //row has been updated

}

catch(Exception e){

System.out.println(e);

return 0;

}

}

public int updateIngredient(Ingredient ingredient) throws SQLException {

// Should simply call the previous method

return updateIngredient(ingredient.getID(),ingredient.getName(),ingredient.getQuantity(),ingredient.getUnitsAndStyle());

}

 

/*

* TODO:        This method should try to delete an existing Recipe with the details

*                                 provided by the parameters

*         @param           Ingredient ID

*  @throws    SQLException

*/

public int deleteIngredient(int ingredientID) throws SQLException {

try

{

String sql=”DELETE FROM recipeIngredients WHERE ID='”+ingredientID+”‘”;

statement.execute(sql);

return 1; //row has been deleted

}

catch(Exception e){

System.out.println(e);

return 0;

}

}

public int deleteIngredient(Ingredient ingredient) throws SQLException {

// Should simply call the previous method

return deleteIngredient(ingredient.getID());

}

 

/*

* TODO:        This method should try to add a new Recipe with the details

*                                 provided by the parameters

*         @param           All the details of the recipe to be added (except the id)

*         @return           The id of the recipe (which is generated by the database)

*  @throws    SQLException

*/

public int addRecipe(String name, int serves, String steps, String remarks) throws SQLException

{

try

{

String sql=”INSERT INTO recipes (name,serves,steps,remarks) VALUES (‘”+name+”‘,'”+serves+”‘,'”+steps+”‘,'”+remarks+”‘)”;

statement.execute(sql);

ResultSet rs = statement.executeQuery(“SELECT ID FROM recipes ORDER BY ID DESC LIMIT 1”);

int id=0;

//loop

while(rs.next()){

id=rs.getInt(“ID”);

}

return id;

}

catch(Exception e){

System.out.println(e);

return 0;

}

}

 

/*

* TODO:        This method should try to add the given Recipe to the database.

* @param       recipe – The recipe object which contains details of the new recipe

* @throws     SQLException

*/

 

public int addRecipe(Recipe recipe) throws SQLException

{

// TO DO

 

// Should simply call the previous method

//          then add each of the ingredients

return addRecipe(recipe.getName(),recipe.getServes(),recipe.getSteps(),recipe.getRemarks());

}

 

/**

* TODO:        This method should try to update an existing Recipe using the

*                                 details provided by the given Recipe parameter. All the details,

*         `                                   except the id, can be updated

* @param       recipe – The Recipe instance that contains details to be used for

*                                 updating

* @throws     SQLException

*/

public void updateRecipe(Recipe recipe) throws SQLException

{

try

{

String sql=”UPDATE recipes SET name='”+recipe.getName()+”‘,serves='”+recipe.getServes()+”‘,steps='”+recipe.getSteps()+”‘,remarks='”+recipe.getRemarks()+”‘ WHERE ID='”+recipe.getID()+”‘ “;

statement.execute(sql);

System.out.println(“Recipe updated”);

}catch(Exception e){

System.out.println(e);

}

}

 

 

/**

* TODO:        This method should try to delete a Recipe  from the database

* @param       id – The id of the Recipe to be deleted

* @throws     SQLException

*/

 

public void deleteRecipe(int id) throws SQLException

{

try

{

String sql=”DELETE FROM recipes WHERE ID='”+id+”‘”;

statement.execute(sql);

}

catch(Exception e){

System.out.println(e);

}

}

 

 

/**

* TODO:        This method should try to delete a Recipe from the database

* @param       recipe – The Recipe object which contains the id of the recipe

*                                             to be deleted

* @throws     SQLException

*/

public void deleteRecipe(Recipe recipe) throws SQLException

{

deleteRecipe(recipe.getID());

}

 

// This method provide a few basic tests of the  DSC class

//

 

public void setUseAlertForInput(boolean value)

{

useAlertForInput = value;

}

 

public static void main(String [] args) throws Exception

{

RecipeDSC dsc = new RecipeDSC();

dsc.setUseAlertForInput(false); //this changes the program to use command prompt instead

dsc.connect();

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 1 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

 

List<Recipe> list = dsc.findAll();

System.out.println(list);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 2 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

Recipe recipe = dsc.find(4);

System.out.println(recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 3 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

recipe = dsc.find(100);

System.out.println(recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 4 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

int ID = dsc.addRecipe(“name 200”, 100, “step 1 , 2, 3, 4”, “easy”);

System.out.println(“ID: ” + ID);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- Test 5 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

int ingredientID = dsc.addIngredient(ID, “ingredient”, 20, “grams”);

System.out.println(“ingredientID: ” + ingredientID);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 6 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

recipe = dsc.find(4);

recipe.setName(“Drunken chicken zoo”);

recipe.setServes(100);

Ingredient i = new Ingredient();

i.setName(“Drunken chicken”);

i.setQuantity(10);

i.setUnitsAndStyle(“”);

recipe.addIngredient(i);

i = new Ingredient();

i.setName(“RICE”);

i.setQuantity(100);

i.setUnitsAndStyle(“kg”);

recipe.addIngredient(i);

 

recipe.setSteps(“\n1. Cook chicken\n2.Cook rice”);

recipe.setRemarks(“Enjoy the festival!”);

 

System.out.println(“>>> updated recipe: ” + recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 7 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

 

dsc.updateRecipe(recipe);

recipe = dsc.find(4);

System.out.println(“>>> updated recipe from database: ” + recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

/*RecipeDSC dsc = new RecipeDSC();

dsc.setUseAlertForInput(false); //this changes the program to use command prompt instead

//dsc.getPassword();

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 1 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

List<Recipe> list = dsc.findAll();

System.out.println(list);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 2 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

Recipe recipe = dsc.find(4);

System.out.println(recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 3 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

recipe = dsc.find(100);

System.out.println(recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 4 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

int ID = dsc.addRecipe(“name 200”, 100, “step 1 , 2, 3, 4”, “easy”);

System.out.println(“ID: ” + ID);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_- Test 5 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

int ingredientID = dsc.addIngredient(ID, “ingredient”, 20, “grams”);

System.out.println(“ingredientID: ” + ingredientID);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 6 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

recipe = dsc.find(4);

recipe.setName(“Drunken chicken zoo”);

recipe.setServes(100);

Ingredient i = new Ingredient();

i.setName(“Drunken chicken”);

i.setQuantity(10);

i.setUnitsAndStyle(“”);

recipe.addIngredient(i);

i = new Ingredient();

i.setName(“RICE”);

i.setQuantity(100);

i.setUnitsAndStyle(“kg”);

recipe.addIngredient(i);

 

recipe.setSteps(“\n1. Cook chicken\n2.Cook rice”);

recipe.setRemarks(“Enjoy the festival!”);

 

System.out.println(“>>> updated recipe: ” + recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ Test 7 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

 

 

dsc.updateRecipe(recipe);

recipe = dsc.find(4);

System.out.println(“>>> updated recipe from database: ” + recipe);

System.out.println(“_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_”);

//*/

}

}

 

 

import recipe.RecipeDSC;

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.*;

import javafx.scene.control.*;

import javafx.scene.layout.*;

import javafx.scene.text.*;

import javafx.geometry.*;

import java.util.*;

import java.io.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javafx.collections.*;

import javafx.collections.transformation.*;

import javafx.scene.control.cell.*;

import javafx.beans.property.*;

 

public class RecipeMain extends Application

{

private ObservableList<Recipe> tableData;

private TableView<Recipe> tableView;

private RecipeDSC recipeDSC;

 

/*public RecipeMain() throws Exception{

start(primaryStage);

}*/

 

@Override

public void start(Stage primaryStage) throws Exception

{

try{

build(primaryStage);

primaryStage.setTitle(getClass().getName());

primaryStage.show();

 

Thread.currentThread().setUncaughtExceptionHandler((thread, exception) ->

{

// System.out.println(“ERROR: ” + exception);

Alert alert = new Alert(Alert.AlertType.WARNING);

alert.setContentText(“Exception thrown: ” + exception);

alert.showAndWait();

});

}catch (Exception e){

System.out.println(e);

}

}

 

public void build(Stage primaryStage) throws Exception

{

loadData();

 

Node searchArea = makeSearchArea();

Node tableViewArea = makeTableView();

Node addViewDeleteArea = makeViewAddDeleteArea(primaryStage);

 

VBox root = makeSceneRoot();

 

root.getChildren().addAll(searchArea, tableViewArea, addViewDeleteArea);

 

Scene scene = new Scene(root);

primaryStage.setScene(scene);

}

 

 

// To load data from the database into tableData

// and tableView

//

private void loadData() throws Exception

{

recipeDSC = new RecipeDSC();

recipeDSC.connect();

List<recipe.Recipe> recipes = recipeDSC.findAll();

 

tableData = FXCollections.observableArrayList();

tableData.clear();

tableData.addAll(recipes);

 

tableView = new TableView<Recipe>();

tableView.setItems(tableData);

}

 

 

// TO DO: Create and return a VBox to be the root of the scene graph

//

private VBox makeSceneRoot()

{

VBox vbox=new VBox();

vbox.setSpacing(10);

vbox.setPadding(new Insets(15,12,15,12));

return vbox;

}

 

 

// TO DO: Create the area to allow the user to search the table view

// The program should provide option to apply the search to every field, or

// to the ingredients, or the recipe names.

//

private Node makeSearchArea()

{

VBox parent=new VBox();

parent.setSpacing(10);

parent.setPadding(new Insets(15,12,15,12));

 

//declare label and textfield

Label label1=new Label(“Enter search text”);

TextField searchField=new TextField();

HBox hbox1=new HBox(label1,searchField);

hbox1.setSpacing(10);

 

//defining the radio buttons

ToggleGroup group=new ToggleGroup();

RadioButton btnAny=new RadioButton(“Any Field”);

btnAny.setToggleGroup(group);

btnAny.setSelected(true);

RadioButton btnIngredients=new RadioButton(“Ingredients”);

RadioButton btnRecipe=new RadioButton(“Recipe Name”);

btnIngredients.setToggleGroup(group);

btnRecipe.setToggleGroup(group);

HBox hbox2=new HBox(btnAny,btnIngredients,btnRecipe);

 

parent.getChildren().addAll(hbox1, hbox2);

 

 

return parent;

}

 

 

//

// TO DO: Define the table view and put it in a hbox

//

private Node makeTableView()

{

VBox parent=new VBox();

parent.setSpacing(10);

parent.setPadding(new Insets(15,12,15,12));

 

TableView tableview=new TableView();

parent.getChildren().add(tableview);

return parent;

}

 

 

// TO DO: Create the area with the buttons to view, add and delete reviews

//

private Node makeViewAddDeleteArea(Stage primaryStage)

{

HBox parent=new HBox();

parent.setSpacing(10);

parent.setPadding(new Insets(15,12,15,12));

 

Button btnViewUpdate=new Button(“view/ update selected recipe”);

Button  btnAddRecipe=new Button(“Add recipe “);

Button btndelRecipe=new Button(“Delete selected recipe”);

 

//adding event listeners

btnViewUpdate.setOnAction(e->{

System.out.println(“Working”);

try {

new RecipeStageMaker(recipeDSC,tableData,tableView,primaryStage).showViewRecipeStage();

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

btnAddRecipe.setOnAction(e->{

try {

new RecipeStageMaker(recipeDSC,tableData,tableView,primaryStage).showAddRecipeStage();

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

btnAddRecipe.setOnAction(e->{

try {

new RecipeStageMaker(recipeDSC,tableData,tableView,primaryStage).showDeleteRecipeStage();

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

parent.getChildren().addAll(btnViewUpdate,btnAddRecipe,btndelRecipe);

return parent;

}

 

public static void main(String[] args){

Application.launch(args);

}

 

}

 

/*

This class is used to define and show three stages: one to view and/od update

a recipe, one to add a ne recipe, and one to delete a recipe.

*/

 

 

import recipe.RecipeDSC;

import javafx.application.Application;

import javafx.stage.*;

import javafx.scene.*;

import javafx.scene.control.*;

import javafx.scene.layout.*;

import javafx.scene.text.*;

import javafx.geometry.*;

import java.util.*;

import java.io.*;

import java.util.logging.Level;

import java.util.logging.Logger;

import javafx.collections.*;

import javafx.collections.transformation.*;

import javafx.scene.control.cell.*;

import javafx.beans.property.*;

 

public class RecipeStageMaker extends Application

{

private RecipeDSC recipeDSC;

private ObservableList<Recipe> tableData;

private TableView<Recipe> tableView;

private Stage primaryStage;

 

// id

private Label idLB = new Label(“Id: “);

private TextField idTF = new TextField();

private HBox idHBox = new HBox(idLB, idTF);

 

// name

private Label nameLB = new Label(“Recipe Name: “);;

private TextField nameTF = new TextField();

private HBox nameHBox = new HBox(nameLB, nameTF);

 

// serves

private Label servesLB = new Label(“Serves: “);

private TextField servesTF = new TextField();

private HBox servesHBox = new HBox(servesLB, servesTF);

 

// ingredients

private Label ingredientsLB = new Label(“Ingredients”);

private TableView<Ingredient> ingredientsTbl = new TableView<>();

private Button ingredientsAdd = new Button(“Add Ingredient”);

private Button ingredientsEdd = new Button(“Edit Ingredient”);

private Button ingredientsDel = new Button(“Delete Ingredient”);

private VBox ingredientButtons = new VBox(ingredientsAdd, ingredientsEdd, ingredientsDel);

private VBox ingredientsLblAndTbl = new VBox(ingredientsLB, ingredientsTbl);

private HBox ingredientsHBox = new HBox(ingredientsLblAndTbl, ingredientButtons);

 

// steps

private TextArea stepsTA = new TextArea();

private HBox stepsHBox = new HBox(stepsTA);

 

// remarks

private Label remarksLB = new Label(“Remarks: “);

private TextField remarksTF = new TextField();

private HBox remarksHBox = new HBox(remarksLB, remarksTF);

 

// action buttons

private Button addBT = new Button(“ADD Recipe”);

private Button updateBT = new Button(“UPDATE Recipe”);

private Button deleteBT = new Button(“DELETE Recipe”);

private Button cancelBT = new Button(“EXIT/CANCEL”);

private HBox actionHBox = new HBox();

 

 

// root, scene, local stage

private VBox root = new VBox();

private Scene scene = new Scene(root);

private Stage stage = new Stage();

 

public RecipeStageMaker(RecipeDSC recipeDSC, ObservableList<Recipe> tableData, TableView<Recipe> tableView, Stage primaryStage )

{

/*

* TO DO: Initilize the RecipeStageMaker

* (can include the setting of style rules if choose to do so)

*/

 

this.recipeDSC=recipeDSC;

this.tableData=tableData;

this.tableView=tableView;

this.primaryStage=primaryStage;

}

 

public void showViewRecipeStage() throws Exception

{

/*

* TO DO: To present a stage to view and/or update the recipe selected

* in the table view

*/

actionHBox = new HBox(updateBT,cancelBT);

VBox vbox=new VBox(idHBox,nameHBox,servesHBox,ingredientsHBox,stepsHBox,remarksHBox,actionHBox);

vbox.setSpacing(10);

vbox.setPadding(new Insets(15,12,15,12));

 

cancelBT.setOnAction(e->{

try {

new RecipeMain().start(primaryStage);

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

Scene scene = new Scene(vbox);

primaryStage.setScene(scene);

primaryStage.show();

 

}

 

public void showAddRecipeStage()

{

/*

* TO DO: To present a stage to add a recipe

*/

actionHBox = new HBox(addBT,cancelBT);

VBox vbox=new VBox(idHBox,nameHBox,servesHBox,ingredientsHBox,stepsHBox,remarksHBox,actionHBox);

vbox.setSpacing(10);

vbox.setPadding(new Insets(15,12,15,12));

 

cancelBT.setOnAction(e->{

try {

new RecipeMain().start(primaryStage);

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

Scene scene = new Scene(vbox);

primaryStage.setScene(scene);

primaryStage.show();

}

 

public void showDeleteRecipeStage()

{

/*

* TO DO: To present a stage to delete the recipe selected in

* the table view

*/

actionHBox = new HBox(deleteBT,cancelBT);

VBox vbox=new VBox(idHBox,nameHBox,servesHBox,ingredientsLblAndTbl,stepsHBox,remarksHBox,actionHBox);

vbox.setSpacing(10);

vbox.setPadding(new Insets(15,12,15,12));

 

cancelBT.setOnAction(e->{

try {

new RecipeMain().start(primaryStage);

} catch (Exception ex) {

Logger.getLogger(RecipeMain.class.getName()).log(Level.SEVERE, null, ex);

}

});

 

Scene scene = new Scene(vbox);

primaryStage.setScene(scene);

primaryStage.show();

}

 

@Override

public void start(Stage stage) throws Exception {

throw new UnsupportedOperationException(“Not supported yet.”); //To change body of generated methods, choose Tools | Templates.

}

public static void main(String[] args){

Application.launch();

}

}

 

 

 

 

—          This is a MySQL script to

—                      Create a database

—                      Create a table

—                      Add some data to the table

 

— for personal computers

DROP database if EXISTS recipeDB;

CREATE database recipeDB;

USE recipeDB;

 

— for unix account

— USE <your Student Database>;

— DROP TABLE IF EXISTS recipeIngredients

— DROP TABLE IF EXISTS recipes

 

CREATE TABLE recipes(

ID INT auto_increment,

name VARCHAR(50) NOT NULL,

serves int,

steps TEXT,

remarks VARCHAR(100),

PRIMARY KEY (ID)

);

 

CREATE TABLE recipeIngredients(

ID INT NOT NUll auto_increment,

recipeID INT NOT NULL,

name VARCHAR(100) NOT NULL,

quantity DECIMAL(6,2) NOT NULL,

unitsAndStyle VARCHAR(50) NOT NULL,

PRIMARY KEY (ID),

FOREIGN KEY (recipeID) REFERENCES recipes(ID)

);

 

— Populate the database with some data

 

INSERT INTO recipes           (name, serves, steps, remarks) — nr 1

VALUES(‘Breakfast Quinoa’, 3,

“\nBring milk to a boil\nAdd quinoa and return to a boil\nSimmer for 15 minutes\nAdd 3/4 of banana and raspberries\nCook until all milk is absorbed\nAdd remaing banana and raspberries”,

‘1300 KJ per serve’

);

— create a sql variable using a select statement to get the auto incremented ID of the ‘Breakfast Quinoa’ recipe

Select @currentRecipeID := ID FROM recipes WHERE name = ‘Breakfast Quinoa’;

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘ALMOND MILK’, 2, ‘cups’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘QUINOA’, 1, ‘cup’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘BANANA’, 1, ‘sliced’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘RASPBEERRIES’, 1, ‘cup’);

 

INSERT INTO recipes           (name, serves, steps, remarks) — nr 2

VALUES( ‘Sweet Potato Ham Fritters’, 4,

‘\n1. Beat the eggs in a large bowl.\n2. Add sweet potato and ham.\n3. heat 2 spoons of oive oil in  frying pan.\n4. Spoon the batter and cook until brown on each side.’,

‘High in fibre, low in carbohydrate’

);

Select @currentRecipeID := ID FROM recipes WHERE name = ‘Sweet Potato Ham Fritters’;

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘EGGS’, 4, ”);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘SWEET POTATO’, 2, ‘cups mashed’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘SMOKE HAM’, 100, ‘grams’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘OLIVE OIL’, 1, ‘tbs’);

 

 

INSERT INTO recipes           (name, serves, steps, remarks) — nr 3

VALUES( ‘Yoghurt Parfait’, 1,

‘\nMix brown rice and yoghurt\nAdd blueberries and almond\nSpoon into a parfait glass to serve’,

‘1628 KJ per serve’

);

Select @currentRecipeID := ID FROM recipes WHERE name = ‘Yoghurt Parfait’;

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘BROWN RICE’, 0.5, ‘cups cooked’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘FAT-FREE YOGHURT’, 100 , ‘grams’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘BLUEBERRIES’, 50, ‘grams’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘ALMOND’, 30 , ‘grams’);

 

INSERT INTO recipes           (name, serves, steps, remarks) — nr 4

VALUES(‘Balsamic Chicken with Creamy Mash’, 4,

‘\nSlice chicken into thin tenderloins\nMarinate in vinegar for 20 minutes\nHeat chicken at 180 degrees for 10 minuts\nPeel potato and boil them until tender\nDrain potato, and mash until smooth\nAdd chopped avacado and mash\nSpoon mash into a bowl and top with chicken strips’,

‘Low in energy’

);

Select @currentRecipeID := ID FROM recipes WHERE name = ‘Balsamic Chicken with Creamy Mash’;

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘CHICKEN BREAST’, 500, ‘grams’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘BALSAMIC VINEGAR’, 0.25 , ‘cup’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘GOLD POTATO’, 700, ‘grams’);

INSERT INTO recipeIngredients (recipeID, name, quantity, unitsAndStyle)

Values (@currentRecipeID, ‘AVOCADO’, 300, ‘grams’);

 

 

— to verify

SELECT * FROM recipes;