Skip to content
Snippets Groups Projects
Commit fd22be70 authored by Karsch Lukas's avatar Karsch Lukas
Browse files

Save image path in JSON file

parent add94ce1
No related branches found
No related tags found
No related merge requests found
Showing
with 90 additions and 72 deletions
......@@ -63,12 +63,14 @@ public class GUIDriver extends Application {
stage.setScene(scene);
stage.show();
//set app icon
InputStream iconStream = getClass().getResourceAsStream(PATH_TO_ICON);
if (iconStream != null) {
stage.getIcons().add(new Image(iconStream));
log.debug("Set icon for application");
} else log.warn("Could not find icon for application. Check the filepath");
//set up music
runnable = new MusicPlayer(FILE_NAME);
musicThread = new Thread(runnable);
musicThread.setDaemon(true);
......@@ -107,22 +109,4 @@ public class GUIDriver extends Application {
log.debug("Playing music");
runnable.play();
}
/*public static void toggleCurrentMusicState() {
musicIsOn = !musicIsOn;
synchronized (musicThread) {
if(musicIsOn) {
log.debug("Notifying music thread");
musicThread.notify();
} else {
try {
log.debug("Letting music thread wait...");
musicThread.wait();
} catch (InterruptedException e) {
log.error("Could not pause music: {}", e.getMessage());
e.printStackTrace();
}
}
}
}*/
}
......@@ -35,21 +35,18 @@ public class MusicPlayer implements Runnable {
try {
audioInputStream = getAudioInputStream(absoluteFilePath);
} catch (Exception e) {
e.printStackTrace();
}
if (audioInputStream == null) {
log.error("No audio input stream found for this system! Music can't be played");
return;
}
AudioFormat audioFormat = audioInputStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
final AudioFormat audioFormat = audioInputStream.getFormat();
final DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
//get ready to write audio data
line = (SourceDataLine) AudioSystem.getLine(info);
} catch (Exception e) {
e.printStackTrace();
log.error("Could not obtain line for audio playback. Exiting music thread");
return;
}
assert line != null;
int nBytesRead;
try {
line.open(audioInputStream.getFormat());
......@@ -77,6 +74,13 @@ public class MusicPlayer implements Runnable {
line.drain();
line.close();
log.debug("Drained and closed audio line");
try {
audioInputStream.close();
log.info("Closed audio stream");
} catch (IOException e) {
log.error("Closing the audio stream caused an IO exception: {}", e.getMessage());
log.error("Cause: {}", e.getCause().toString());
}
}
}
......
package mi.hdm;
import mi.hdm.filesystem.FileManager;
import mi.hdm.mealPlan.MealPlan;
import mi.hdm.recipes.*;
import mi.hdm.recipes.CategoryManager;
import mi.hdm.recipes.IngredientManager;
import mi.hdm.recipes.RecipeManager;
import mi.hdm.shoppingList.ShoppingList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
/**
* This class contains all the services in the application: recipe manager, ingredient manager, shopping list,
* category manager and meal plan.
......
......@@ -10,6 +10,7 @@ import mi.hdm.recipes.Category;
import mi.hdm.recipes.CategoryManager;
import mi.hdm.recipes.Recipe;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
......@@ -42,7 +43,13 @@ public class RecipeVbox extends VBox {
categoryFlowPane.setHgap(5.0);
categoryFlowPane.getChildren().addAll(categoryLabels);
ImageView recipeImage = new ImageView(new Image(recipe.getImageURL().toString()));
URL imageUrl = recipe.getImageURL();
ImageView recipeImage;
if (imageUrl != null) {
recipeImage = new ImageView(new Image(recipe.getImageURL().toString()));
} else {
recipeImage = new ImageView(new Image(Recipe.class.getResource("/images/dish-fork-and-knife.png").toString()));
}
recipeImage.setPreserveRatio(true);
recipeImage.setFitWidth(150);
recipeImage.setFitHeight(150);
......
......@@ -13,6 +13,9 @@ import mi.hdm.recipes.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.net.URL;
import java.util.stream.IntStream;
//TODO: display nutrition table in here (using "fxml/components/nutrition-table.fxml", see ViewComponent and MealPlan)
public class RecipeViewController extends BaseController {
private static final Logger log = LogManager.getLogger(RecipeViewController.class);
......@@ -51,7 +54,10 @@ public class RecipeViewController extends BaseController {
recipeName.setText(recipe.getName());
recipeDescription.setText(recipe.getDescription());
recipePreparation.setText(String.join("\n", recipe.getPreparation()));
String preparation = IntStream.range(0, recipe.getPreparation().size())
.mapToObj(idx -> String.format("%d. %s%n", idx + 1, recipe.getPreparation().get(idx)))
.reduce("", String::concat);
recipePreparation.setText(preparation);
recipe.getIngredients().forEach((code, amount) -> {
Ingredient i = ingredientManager.getIngredient(code).orElseThrow();
......@@ -66,9 +72,14 @@ public class RecipeViewController extends BaseController {
});
//idea for solution from: https://stackoverflow.com/questions/22710053/how-can-i-show-an-image-using-the-imageview-component-in-javafx-and-fxml
log.debug("Trying to load image for recipe from '{}'", recipe.getImageURL());
recipeImage.setImage(new Image(recipe.getImageURL().toString()));
recipeImage.setPreserveRatio(true);
URL imageURL = recipe.getImageURL();
if (imageURL != null) {
log.debug("Trying to load image for recipe from '{}'", imageURL);
recipeImage.setImage(new Image(imageURL.toString()));
recipeImage.setPreserveRatio(true);
} else {
recipeImage.setImage(new Image(Recipe.class.getResource("/images/dish-fork-and-knife.png").toString()));
}
recipeImage.setFitHeight(180);
putNutritionTable(nutritionTableContainer, recipe.getNutritionTable(), "Nutrition score for this recipe", 1);
}
......
......@@ -327,14 +327,14 @@ public class FileManager {
return gson.fromJson(json, Recipe.class);
}
public static String getAbsolutePathFromResourceFolder(String p) {
public static String getAbsolutePathFromResourceFolder(String relativePath) {
try {
URL resourceUrl = FileManager.class.getResource(p);
URL resourceUrl = FileManager.class.getResource(relativePath);
assert resourceUrl != null;
Path path = Paths.get(resourceUrl.toURI());
return path.toFile().getAbsolutePath();
} catch (URISyntaxException e) {
log.error("Absolute path for \"{}\" not found", p);
log.error("Absolute path for \"{}\" not found, returning null", relativePath);
return null;
}
}
......
......@@ -22,7 +22,7 @@ public class Recipe implements RecipeComponent {
private NutritionTable nutritionTable;
private final LocalDateTime creationTime;
private URL filepathForImage;
private URL filepathForImage = null;
/**
* This constructor will create a new recipe and calculate the nutrition values for the recipe by its ingredients.
......@@ -42,7 +42,7 @@ public class Recipe implements RecipeComponent {
List<Category> categories,
Integer preparationTimeMins) {
//Das ruft den anderen Konstruktor dieser Klasse auf (siehe unten)
//Calculates nutrition table and calls the constructor below
this(name, ingredients, description, preparation, categories, preparationTimeMins, NutritionCalculator.calculateNutritionTable(ingredients));
}
......@@ -76,8 +76,6 @@ public class Recipe implements RecipeComponent {
this.creationTime = LocalDateTime.now();
this.code = calculateUniqueCode();
filepathForImage = Recipe.class.getResource("/images/dish-fork-and-knife.png");
}
public Recipe(
......@@ -100,7 +98,6 @@ public class Recipe implements RecipeComponent {
setCategories(categories);
this.creationTime = creationTime;
this.code = code;
filepathForImage = Recipe.class.getResource("/images/dish-fork-and-knife.png");
}
public void setName(String name) {
......@@ -150,7 +147,7 @@ public class Recipe implements RecipeComponent {
}
public void addCategory(Category category) {
if (!categories.contains(category)) {
if (!categories.contains(category.getCode())) {
categories.add(category.getCode());
log.info("Category {} added successfully.", category.getName());
} else {
......
......@@ -10,6 +10,9 @@ import mi.hdm.recipes.NutritionTable;
import mi.hdm.recipes.Recipe;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
......@@ -21,16 +24,22 @@ public class RecipeTypeAdapter extends TypeAdapter<Recipe> {
writer.name("name").value(recipe.getName());
writer.name("nutritionTable").jsonValue(new GsonBuilder().registerTypeAdapter(NutritionTable.class, new NutritionTableTypeAdapter()).create().toJson(recipe.getNutritionTable()));
writer.name("code").value(recipe.getUniqueCode());
writer.name("ingredients").jsonValue(new Gson().toJson(recipe.getIngredients()));
writer.name("description").value(recipe.getDescription());
writer.name("preparation").jsonValue(new Gson().toJson(recipe.getPreparation()));
writer.name("categories").jsonValue(new Gson().toJson(recipe.getCategoryCodes()));
writer.name("preparationTimeMins").value(recipe.getPreparationTimeMins());
writer.name("creationTime").value(recipe.getCreationTime().toString());
URL imageUrl = recipe.getImageURL();
if (imageUrl == null) {
writer.name("imagePath").nullValue();
} else {
try {
writer.name("imagePath").value(recipe.getImageURL().toURI().toString());
} catch (URISyntaxException e) {
writer.name("imagePath").nullValue();
}
}
writer.endObject();
}
......@@ -45,6 +54,7 @@ public class RecipeTypeAdapter extends TypeAdapter<Recipe> {
NutritionTable nutritionTable = null;
LocalDateTime creationTime = null;
String code = null;
URL imagePath = null;
reader.beginObject();
while (reader.hasNext()) {
......@@ -80,6 +90,12 @@ public class RecipeTypeAdapter extends TypeAdapter<Recipe> {
case "code":
code = reader.nextString();
break;
case "imagePath":
try {
imagePath = new URI(reader.nextString()).toURL();
} catch (URISyntaxException e) {
imagePath = null;
}
default:
reader.skipValue();
break;
......@@ -87,6 +103,8 @@ public class RecipeTypeAdapter extends TypeAdapter<Recipe> {
}
reader.endObject();
return new Recipe(name, ingredients, description, preparation, categories, preparationTimeMins, nutritionTable, creationTime, code);
Recipe output = new Recipe(name, ingredients, description, preparation, categories, preparationTimeMins, nutritionTable, creationTime, code);
output.setImage(imagePath);
return output;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane fx:id="parent" prefHeight="700.0" prefWidth="1000.0" style="-fx-background-color: 000000;" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mi.hdm.controllers.CategoryCreatorController">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</padding>
<VBox prefHeight="200.0" prefWidth="100.0" spacing="5.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="50.0" AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="50.0">
<Label text="Create a category">
<font>
<Font name="System Bold" size="24.0" />
</font>
</Label>
<Label text="Name for your category" />
<?import javafx.scene.text.Font?>
<AnchorPane fx:id="parent" prefHeight="700.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/17.0.2-ea"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="mi.hdm.controllers.CategoryCreatorController">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<VBox prefHeight="200.0" prefWidth="100.0" spacing="5.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="50.0"
AnchorPane.rightAnchor="50.0" AnchorPane.topAnchor="50.0">
<Label text="Create a category">
<font>
<Font name="System Bold" size="24.0"/>
</font>
</Label>
<Label text="Name for your category"/>
<HBox prefWidth="200.0" spacing="20.0">
<VBox.margin>
<Insets top="5.0" />
......
......@@ -4,9 +4,10 @@
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<AnchorPane fx:id="parent" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: 000000;" xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="mi.hdm.controllers.IngredientCreatorController">
<AnchorPane fx:id="parent" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/17.0.2-ea"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="mi.hdm.controllers.IngredientCreatorController">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<BorderPane prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0"
AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="40.0">
......
......@@ -4,10 +4,10 @@
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.Font?>
<AnchorPane fx:id="parent" prefHeight="700.0" prefWidth="1000.0" style="-fx-background-color: ffffff;"
<AnchorPane fx:id="parent" prefHeight="700.0" prefWidth="1000.0"
xmlns="http://javafx.com/javafx/17.0.2-ea" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="mi.hdm.controllers.ShoppingListViewController">
<VBox layoutX="123.0" prefHeight="539.0" prefWidth="872.0" style="-fx-background-color: ffffff;"
<VBox layoutX="123.0" prefHeight="539.0" prefWidth="872.0" style="-fx-background-color: #ffffff;"
AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0">
<padding>
......
......@@ -9,11 +9,11 @@ import java.util.List;
import java.util.Map;
public class NutritionCalculatorTest {
private List<RecipeComponent> ingredients = ValidObjectsPool.getValidIngredientList();
private final List<RecipeComponent> ingredients = ValidObjectsPool.getValidIngredientList();
private Map<RecipeComponent, Integer> recipeMap;
private final RecipeManager recipeManager = new RecipeManager();
private Recipe recipe = ValidObjectsPool.getValidRecipeOne();
private final Recipe recipe = ValidObjectsPool.getValidRecipeOne();
@BeforeEach
public void setUp() {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment