rename modules according to rules

This commit is contained in:
2022-07-22 01:01:21 +02:00
parent 6d6d060d5b
commit 11c1e022b6
51 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,20 @@
package spoonaccular;
import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.Request;
public class APIAuthentication {
private static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load();
private APIAuthentication(){
}
public static Request.Builder addAuthHeaders(Request.Builder builder){
return builder
.get()
.addHeader("X-RapidAPI-Key", dotenv.get("X-RapidAPI-Key"))
.addHeader("X-RapidAPI-Host", dotenv.get("X-RapidAPI-Host"));
}
}

View File

@@ -0,0 +1,39 @@
package spoonaccular;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import spoonaccular.models.amount_conversion.ConvertedAmount;
import java.io.IOException;
public class AmountConversion {
private static final OkHttpClient client = new OkHttpClient();
private static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load();
private AmountConversion(){
}
public static double convertAmount(String ingrdientName, Double sourceAmount, String sourceUnit, String targetUnit) throws IOException {
Request request = APIAuthentication.addAuthHeaders(
new Request.Builder()
.url("https://" + dotenv.get("X-RapidAPI-Host") +
"/recipes/convert?ingredientName=" + ingrdientName +
"&targetUnit=" + targetUnit +
"&sourceUnit=" + sourceUnit +
"&sourceAmount=" + sourceAmount)
).build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
try {
return new ObjectMapper().readValue(responseString, ConvertedAmount.class).getTargetAmount();
} catch (Exception e){
return 0;
}
}
}

View File

@@ -0,0 +1,72 @@
package spoonaccular;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import spoonaccular.models.ingredients_by_id.Ingredient;
import spoonaccular.models.recipe_by_ingredient.ExtendedRecipeByIngredient;
import spoonaccular.models.recipe_by_ingredient.RecipeByIngredient;
import spoonaccular.models.recipe_information.Recipe;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class RecipeInformation {
private final static Dotenv dotenv = Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load();
private final static OkHttpClient client = new OkHttpClient();
private RecipeInformation(){
}
public static List<Recipe> getRecipeFromIds(List<Integer> ids) throws IOException {
String idsString = ids.stream().map(String::valueOf)
.collect(Collectors.joining(","));
return new ObjectMapper().readValue(queryInformationBulk(idsString).body().string(), new TypeReference<>(){});
}
public static List<ExtendedRecipeByIngredient> getExtendedRecipeFromIds(List<Integer> ids) throws IOException {
String idsString = ids.stream().map(String::valueOf)
.collect(Collectors.joining(","));
return new ObjectMapper().readValue(queryInformationBulk(idsString).body().string(), new TypeReference<>() {});
}
public static List<Ingredient> getIngredientList(int recipeId) throws IOException, JSONException {
Request request = APIAuthentication.addAuthHeaders(new Request.Builder()
.url("https://" + dotenv.get("X-RapidAPI-Host") +
"/recipes/" + recipeId + "/ingredientWidget.json"))
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return new ObjectMapper().readValue(jsonObject.getJSONArray("ingredients").toString(), new TypeReference<>() {});
}
private static Response queryInformationBulk(String idsString) throws IOException {
Request request = APIAuthentication.addAuthHeaders(new Request.Builder()
.url("https://" + dotenv.get("X-RapidAPI-Host") +
"/recipes/informationBulk?ids=" + idsString))
.build();
return client.newCall(request).execute();
}
public static List<ExtendedRecipeByIngredient> getRecepieByIngredientsExtended(List<RecipeByIngredient> recipeByIngredients) throws IOException {
List<Integer> ids = recipeByIngredients.stream().map(RecipeByIngredient::getId).toList();
List<ExtendedRecipeByIngredient> extendedRecipeByIngredients = getExtendedRecipeFromIds(ids);
Iterator<RecipeByIngredient> recipeByIngredientIterator = recipeByIngredients.iterator();
Iterator<ExtendedRecipeByIngredient> extendedRecipeByIngredientIterator = extendedRecipeByIngredients.iterator();
while(recipeByIngredientIterator.hasNext() && extendedRecipeByIngredientIterator.hasNext()){
extendedRecipeByIngredientIterator.next().addMissingInfo(recipeByIngredientIterator.next());
}
return extendedRecipeByIngredients;
}
}

View File

@@ -0,0 +1,69 @@
package spoonaccular;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.cdimascio.dotenv.Dotenv;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import spoonaccular.models.recipe_by_ingredient.ExtendedRecipeByIngredient;
import spoonaccular.models.recipe_by_ingredient.RecipeByIngredient;
import spoonaccular.models.recipe_information.Recipe;
import whattocook.models.Item;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
@Component
public class RecipeSearch {
private static final boolean IGNOREPANTRY = true;
private static final Random rnd = new Random();
private static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load();
private static final OkHttpClient client = new OkHttpClient();
private RecipeSearch(){
}
public static List<ExtendedRecipeByIngredient> getForIngridients(Iterable<Item> items, int number) throws java.io.IOException {
List<String> itemNames = new LinkedList<>();
items.forEach(item -> itemNames.add(item.getName()));
String ingridients = String.join(",", itemNames);
Request request =
APIAuthentication.addAuthHeaders(new Request.Builder()
.url("https://" + dotenv.get("X-RapidAPI-Host") +
"/recipes/findByIngredients?ingredients="
+ ingridients + "&number=" + number + "&ignorePantry="
+ IGNOREPANTRY + "&ranking=" + dotenv.get("X-RapidAPI-SearchRanking")))
.build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
List<RecipeByIngredient> recipeByIngredients = new ObjectMapper().readValue(responseString, new TypeReference<>(){});
return RecipeInformation.getRecepieByIngredientsExtended(recipeByIngredients);
}
public static ExtendedRecipeByIngredient getOneForIngridients(Iterable<Item> items, int number) throws IOException {
return getForIngridients(items, number).get(rnd.nextInt(number));
}
public static List<Recipe> getRandom(List<String> tags, int number) throws java.io.IOException, JSONException {
String tagString = String.join(",", tags);
Request request = APIAuthentication.addAuthHeaders(new Request.Builder()
.url("https://" + dotenv.get("X-RapidAPI-Host") +
"/recipes/random?number=" + number + "&tags=" + tagString))
.build();
Response response = client.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return new ObjectMapper().readValue(jsonObject.getJSONArray("recipes").toString(), new TypeReference<>(){});
}
}

View File

@@ -0,0 +1,110 @@
package spoonaccular.models.amount_conversion;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"sourceAmount",
"sourceUnit",
"targetAmount",
"targetUnit",
"answer",
"type"
})
@Generated("jsonschema2pojo")
public class ConvertedAmount {
@JsonProperty("sourceAmount")
private Double sourceAmount;
@JsonProperty("sourceUnit")
private String sourceUnit;
@JsonProperty("targetAmount")
private Double targetAmount;
@JsonProperty("targetUnit")
private String targetUnit;
@JsonProperty("answer")
private String answer;
@JsonProperty("type")
private String type;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("sourceAmount")
public Double getSourceAmount() {
return sourceAmount;
}
@JsonProperty("sourceAmount")
public void setSourceAmount(Double sourceAmount) {
this.sourceAmount = sourceAmount;
}
@JsonProperty("sourceUnit")
public String getSourceUnit() {
return sourceUnit;
}
@JsonProperty("sourceUnit")
public void setSourceUnit(String sourceUnit) {
this.sourceUnit = sourceUnit;
}
@JsonProperty("targetAmount")
public Double getTargetAmount() {
return targetAmount;
}
@JsonProperty("targetAmount")
public void setTargetAmount(Double targetAmount) {
this.targetAmount = targetAmount;
}
@JsonProperty("targetUnit")
public String getTargetUnit() {
return targetUnit;
}
@JsonProperty("targetUnit")
public void setTargetUnit(String targetUnit) {
this.targetUnit = targetUnit;
}
@JsonProperty("answer")
public String getAnswer() {
return answer;
}
@JsonProperty("answer")
public void setAnswer(String answer) {
this.answer = answer;
}
@JsonProperty("type")
public String getType() {
return type;
}
@JsonProperty("type")
public void setType(String type) {
this.type = type;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@@ -0,0 +1,59 @@
package spoonaccular.models.ingredients_by_id;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"metric",
"us"
})
@Generated("jsonschema2pojo")
public class Amount {
@JsonProperty("metric")
private Metric metric;
@JsonProperty("us")
private Us us;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("metric")
public Metric getMetric() {
return metric;
}
@JsonProperty("metric")
public void setMetric(Metric metric) {
this.metric = metric;
}
@JsonProperty("us")
public Us getUs() {
return us;
}
@JsonProperty("us")
public void setUs(Us us) {
this.us = us;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@@ -0,0 +1,72 @@
package spoonaccular.models.ingredients_by_id;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"image",
"amount"
})
@Generated("jsonschema2pojo")
public class Ingredient {
@JsonProperty("name")
private String name;
@JsonProperty("image")
private String image;
@JsonProperty("amount")
private Amount amount;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("image")
public String getImage() {
return image;
}
@JsonProperty("image")
public void setImage(String image) {
this.image = image;
}
@JsonProperty("amount")
public Amount getAmount() {
return amount;
}
@JsonProperty("amount")
public void setAmount(Amount amount) {
this.amount = amount;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@@ -0,0 +1,59 @@
package spoonaccular.models.ingredients_by_id;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"value",
"unit"
})
@Generated("jsonschema2pojo")
public class Metric {
@JsonProperty("value")
private Double value;
@JsonProperty("unit")
private String unit;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("value")
public Double getValue() {
return value;
}
@JsonProperty("value")
public void setValue(Double value) {
this.value = value;
}
@JsonProperty("unit")
public String getUnit() {
return unit;
}
@JsonProperty("unit")
public void setUnit(String unit) {
this.unit = unit;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@@ -0,0 +1,59 @@
package spoonaccular.models.ingredients_by_id;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"value",
"unit"
})
@Generated("jsonschema2pojo")
public class Us {
@JsonProperty("value")
private Double value;
@JsonProperty("unit")
private String unit;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("value")
public Double getValue() {
return value;
}
@JsonProperty("value")
public void setValue(Double value) {
this.value = value;
}
@JsonProperty("unit")
public String getUnit() {
return unit;
}
@JsonProperty("unit")
public void setUnit(String unit) {
this.unit = unit;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

View File

@@ -0,0 +1,65 @@
package spoonaccular.models.recipe_by_ingredient;
import com.fasterxml.jackson.annotation.JsonProperty;
import spoonaccular.models.recipe_information.Recipe;
import java.util.List;
public class ExtendedRecipeByIngredient extends Recipe {
@JsonProperty("usedIngredientCount")
private Integer usedIngredientCount;
@JsonProperty("missedIngredientCount")
private Integer missedIngredientCount;
@JsonProperty("missedIngredients")
private List<MissedIngredient> missedIngredients = null;
@JsonProperty("usedIngredients")
private List<UsedIngredient> usedIngredients = null;
@JsonProperty("usedIngredientCount")
public Integer getUsedIngredientCount() {
return usedIngredientCount;
}
@JsonProperty("usedIngredientCount")
public void setUsedIngredientCount(Integer usedIngredientCount) {
this.usedIngredientCount = usedIngredientCount;
}
@JsonProperty("missedIngredientCount")
public Integer getMissedIngredientCount() {
return missedIngredientCount;
}
@JsonProperty("missedIngredientCount")
public void setMissedIngredientCount(Integer missedIngredientCount) {
this.missedIngredientCount = missedIngredientCount;
}
@JsonProperty("missedIngredients")
public List<MissedIngredient> getMissedIngredients() {
return missedIngredients;
}
@JsonProperty("missedIngredients")
public void setMissedIngredients(List<MissedIngredient> missedIngredients) {
this.missedIngredients = missedIngredients;
}
@JsonProperty("usedIngredients")
public List<UsedIngredient> getUsedIngredients() {
return usedIngredients;
}
@JsonProperty("usedIngredients")
public void setUsedIngredients(List<UsedIngredient> usedIngredients) {
this.usedIngredients = usedIngredients;
}
public void addMissingInfo(RecipeByIngredient recipeByIngredient){
this.setMissedIngredientCount(recipeByIngredient.getMissedIngredientCount());
this.setUsedIngredientCount(recipeByIngredient.getUsedIngredientCount());
this.setMissedIngredients(recipeByIngredient.getMissedIngredients());
this.setUsedIngredients(recipeByIngredient.getUsedIngredients());
}
}

View File

@@ -0,0 +1,29 @@
package spoonaccular.models.recipe_by_ingredient;
import com.fasterxml.jackson.annotation.*;
import javax.annotation.Generated;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"name"
})
@Generated("jsonschema2pojo")
public class MissedIngredient {
@JsonProperty("name")
private String name;
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,108 @@
package spoonaccular.models.recipe_by_ingredient;
import com.fasterxml.jackson.annotation.*;
import javax.annotation.Generated;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"id",
"title",
"image",
"usedIngredientCount",
"missedIngredientCount",
"missedIngredients",
"usedIngredients",
})
@Generated("jsonschema2pojo")
public class RecipeByIngredient {
@JsonProperty("id")
private Integer id;
@JsonProperty("title")
private String title;
@JsonProperty("image")
private String image;
@JsonProperty("usedIngredientCount")
private Integer usedIngredientCount;
@JsonProperty("missedIngredientCount")
private Integer missedIngredientCount;
@JsonProperty("missedIngredients")
private List<MissedIngredient> missedIngredients = null;
@JsonProperty("usedIngredients")
private List<UsedIngredient> usedIngredients = null;
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("image")
public String getImage() {
return image;
}
@JsonProperty("image")
public void setImage(String image) {
this.image = image;
}
@JsonProperty("usedIngredientCount")
public Integer getUsedIngredientCount() {
return usedIngredientCount;
}
@JsonProperty("usedIngredientCount")
public void setUsedIngredientCount(Integer usedIngredientCount) {
this.usedIngredientCount = usedIngredientCount;
}
@JsonProperty("missedIngredientCount")
public Integer getMissedIngredientCount() {
return missedIngredientCount;
}
@JsonProperty("missedIngredientCount")
public void setMissedIngredientCount(Integer missedIngredientCount) {
this.missedIngredientCount = missedIngredientCount;
}
@JsonProperty("missedIngredients")
public List<MissedIngredient> getMissedIngredients() {
return missedIngredients;
}
@JsonProperty("missedIngredients")
public void setMissedIngredients(List<MissedIngredient> missedIngredients) {
this.missedIngredients = missedIngredients;
}
@JsonProperty("usedIngredients")
public List<UsedIngredient> getUsedIngredients() {
return usedIngredients;
}
@JsonProperty("usedIngredients")
public void setUsedIngredients(List<UsedIngredient> usedIngredients) {
this.usedIngredients = usedIngredients;
}
}

View File

@@ -0,0 +1,29 @@
package spoonaccular.models.recipe_by_ingredient;
import com.fasterxml.jackson.annotation.*;
import javax.annotation.Generated;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"name"
})
@Generated("jsonschema2pojo")
public class UsedIngredient {
@JsonProperty("name")
private String name;
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,42 @@
package spoonaccular.models.recipe_information;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.*;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"name",
"measures"
})
@Generated("jsonschema2pojo")
public class ExtendedIngredient {
@JsonProperty("name")
private String name;
@JsonProperty("measures")
private Measures measures;
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("measures")
public Measures getMeasures() {
return measures;
}
@JsonProperty("measures")
public void setMeasures(Measures measures) {
this.measures = measures;
}
}

View File

@@ -0,0 +1,31 @@
package spoonaccular.models.recipe_information;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.*;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"metric"
})
@Generated("jsonschema2pojo")
public class Measures {
@JsonProperty("metric")
private Metric metric;
@JsonProperty("metric")
public Metric getMetric() {
return metric;
}
@JsonProperty("metric")
public void setMetric(Metric metric) {
this.metric = metric;
}
}

View File

@@ -0,0 +1,42 @@
package spoonaccular.models.recipe_information;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.*;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"amount",
"unitShort"
})
@Generated("jsonschema2pojo")
public class Metric {
@JsonProperty("amount")
private Double amount;
@JsonProperty("unitShort")
private String unitShort;
@JsonProperty("amount")
public Double getAmount() {
return amount;
}
@JsonProperty("amount")
public void setAmount(Double amount) {
this.amount = amount;
}
@JsonProperty("unitShort")
public String getUnitShort() {
return unitShort;
}
@JsonProperty("unitShort")
public void setUnitShort(String unitShort) {
this.unitShort = unitShort;
}
}

View File

@@ -0,0 +1,163 @@
package spoonaccular.models.recipe_information;
import java.util.List;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.*;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
"vegetarian",
"vegan",
"glutenFree",
"dairyFree",
"extendedIngredients",
"id",
"title",
"readyInMinutes",
"servings",
"image",
"sourceUrl",
"spoonacularSourceUrl"
})
@Generated("jsonschema2pojo")
public class Recipe {
@JsonProperty("vegetarian")
private Boolean vegetarian;
@JsonProperty("vegan")
private Boolean vegan;
@JsonProperty("glutenFree")
private Boolean glutenFree;
@JsonProperty("dairyFree")
private Boolean diaryFree;
@JsonProperty("extendedIngredients")
private List<ExtendedIngredient> extendedIngredients = null;
@JsonProperty("id")
private Integer id;
@JsonProperty("title")
private String title;
@JsonProperty("readyInMinutes")
private Integer readyInMinutes;
@JsonProperty("servings")
private Integer servings;
@JsonProperty("image")
private String image;
@JsonProperty("sourceUrl")
private String sourceUrl;
@JsonProperty("spoonacularSourceUrl")
private String spoonacularSourceUrl;
@JsonProperty("vegetarian")
public Boolean getVegetarian() {
return vegetarian;
}
@JsonProperty("vegetarian")
public void setVegetarian(Boolean vegetarian) {
this.vegetarian = vegetarian;
}
@JsonProperty("vegan")
public Boolean getVegan() {
return vegan;
}
@JsonProperty("vegan")
public void setVegan(Boolean vegan) {
this.vegan = vegan;
}
@JsonProperty("glutenFree")
public Boolean getGlutenFree() {
return glutenFree;
}
@JsonProperty("glutenFree")
public void setGlutenFree(Boolean glutenFree) {
this.glutenFree = glutenFree;
}
@JsonProperty("extendedIngredients")
public List<ExtendedIngredient> getExtendedIngredients() {
return extendedIngredients;
}
@JsonProperty("extendedIngredients")
public void setExtendedIngredients(List<ExtendedIngredient> extendedIngredients) {
this.extendedIngredients = extendedIngredients;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("readyInMinutes")
public Integer getReadyInMinutes() {
return readyInMinutes;
}
@JsonProperty("readyInMinutes")
public void setReadyInMinutes(Integer readyInMinutes) {
this.readyInMinutes = readyInMinutes;
}
@JsonProperty("servings")
public Integer getServings() {
return servings;
}
@JsonProperty("servings")
public void setServings(Integer servings) {
this.servings = servings;
}
@JsonProperty("image")
public String getImage() {
return image;
}
@JsonProperty("image")
public void setImage(String image) {
this.image = image;
}
@JsonProperty("spoonacularSourceUrl")
public String getSpoonacularSourceUrl() {
return spoonacularSourceUrl;
}
@JsonProperty("spoonacularSourceUrl")
public void setSpoonacularSourceUrl(String spoonacularSourceUrl) {
this.spoonacularSourceUrl = spoonacularSourceUrl;
}
@JsonProperty("sourceUrl")
public String getSourceUrl() {
return sourceUrl;
}
@JsonProperty("sourceUrl")
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
}

View File

@@ -0,0 +1,37 @@
package whattocook;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Collections;
@SpringBootApplication(scanBasePackages = {"spoonaccular", "whattocook"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// Fix the CORS errors
@Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// *** URL below needs to match the Vue client URL and port ***
config.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedHeaders(Collections.singletonList("*"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}

View File

@@ -0,0 +1,18 @@
package whattocook.configs;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import whattocook.models.Item;
@Configuration
class RepositoryConfig implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.exposeIdsFor(Item.class);
}
}

View File

@@ -0,0 +1,59 @@
package whattocook.controller;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import spoonaccular.AmountConversion;
import spoonaccular.RecipeInformation;
import spoonaccular.models.ingredients_by_id.Ingredient;
import whattocook.models.Item;
import whattocook.services.ItemService;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
@RestController()
@BasePathAwareController()
public class IngredientController {
@Autowired
ItemService itemService;
@DeleteMapping("/ingredient/removeRecipeIngredients")
public List<Item> removeRecipeIngredients(@RequestParam int id) throws IOException, JSONException {
List<Ingredient> ingredientList = RecipeInformation.getIngredientList(id);
List<Item> changedItemList = new LinkedList<>();
for (Ingredient ingredient : ingredientList){
Optional<Item> possibleItem = itemService.findByNameIgnoreCaseContaining(ingredient.getName());
if (possibleItem.isPresent()){
Item item = possibleItem.get();
double newItemQuantity;
//same unit
if (item.getUnit().toString().equals(ingredient.getAmount().getMetric().getUnit())){
newItemQuantity = item.getQuantity() - ingredient.getAmount().getMetric().getValue();
} else {
double ingridientAmount = AmountConversion.convertAmount(ingredient.getName(),
ingredient.getAmount().getMetric().getValue(),
ingredient.getAmount().getMetric().getUnit(),
item.getUnit().toString());
newItemQuantity = item.getQuantity() - ingridientAmount;
}
if (newItemQuantity > 0){
item.setQuantity(newItemQuantity);
itemService.save(item);
} else {
itemService.deleteById(item.getId());
}
changedItemList.add(item);
}
}
return changedItemList;
}
}

View File

@@ -0,0 +1,41 @@
package whattocook.controller;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import spoonaccular.RecipeSearch;
import spoonaccular.models.recipe_by_ingredient.ExtendedRecipeByIngredient;
import spoonaccular.models.recipe_information.Recipe;
import whattocook.repositories.ItemRepository;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
@RestController()
@BasePathAwareController()
public class RecipeSearchController {
private final int nextRecipes=10;
private final int nextRecipesForOneRandom = 20;
@Autowired
private ItemRepository itemRepository;
@GetMapping("/recipe/forFridge")
public List<ExtendedRecipeByIngredient> getForFridge() throws IOException {
return RecipeSearch.getForIngridients(itemRepository.findAll(), nextRecipes);
}
@GetMapping("/recipe/random")
public List<Recipe> getRandom() throws IOException, JSONException {
return RecipeSearch.getRandom(new LinkedList<>(), nextRecipes);
//when user has food preferences apply instead of linked list.
}
@GetMapping("/recipe/oneFridge")
public ExtendedRecipeByIngredient getOneFridge() throws IOException {
return RecipeSearch.getOneForIngridients(itemRepository.findAll(), nextRecipesForOneRandom);
}
}

View File

@@ -0,0 +1,23 @@
package whattocook.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ItemNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ItemNotFoundException(){
super();
}
public ItemNotFoundException(String message) {
super(message);
}
public ItemNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,46 @@
package whattocook.implementation;
import whattocook.models.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import whattocook.repositories.ItemRepository;
import whattocook.services.ItemService;
import java.util.Optional;
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private ItemRepository itemRepository;
@Override
public Item save(Item item) {
return itemRepository.save(item);
}
@Override
public void deleteById(Long id) {
itemRepository.deleteById(id);
}
@Override
public Optional<Item> findById(long id) {
return itemRepository.findById(id);
}
@Override
public Optional<Item> findByName(String name) {
return itemRepository.findByName(name);
}
@Override
public Optional<Item> findByNameIgnoreCaseContaining(String name) {
return itemRepository.findByNameIgnoreCaseContaining(name);
}
@Override
public Iterable<Item> findAll() {
return itemRepository.findAll();
}
}

View File

@@ -0,0 +1,52 @@
package whattocook.models;
import lombok.*;
import org.hibernate.Hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Objects;
@NoArgsConstructor
@Getter
@Setter
@ToString
@Entity
public class Item {
@Setter(AccessLevel.NONE)
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NonNull
private String name;
private Unit unit;
private double quantity;
public Item(String name, Unit unit, double quantity){
this.name = name;
this.unit = unit;
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) {
return false;
}
Item item = (Item) o;
return id != null && Objects.equals(id, item.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,6 @@
package whattocook.models;
public enum Unit {
g,
ml
}

View File

@@ -0,0 +1,13 @@
package whattocook.repositories;
import org.springframework.data.repository.CrudRepository;
import whattocook.models.Item;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface ItemRepository extends CrudRepository<Item, Long> {
Optional<Item> findByName(String name);
Optional<Item> findByNameIgnoreCaseContaining(String name);
}

View File

@@ -0,0 +1,14 @@
package whattocook.services;
import whattocook.models.Item;
import java.util.Optional;
public interface ItemService {
Item save(Item item);
void deleteById(Long id);
Optional<Item> findById(long id);
Optional<Item> findByName(String name);
Optional<Item> findByNameIgnoreCaseContaining(String name);
Iterable<Item> findAll();
}

View File

@@ -0,0 +1,16 @@
server:
port: 9000
spring:
datasource:
url:
username:
password:
driver-class-name:
data:
rest:
base-path: /api/v1
logging:
level:
root: DEBUG

View File

@@ -0,0 +1,107 @@
package items;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import whattocook.models.Item;
import whattocook.models.Unit;
import whattocook.repositories.ItemRepository;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest(classes = whattocook.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
final class ItemTests {
@Autowired
private ItemRepository itemRepository;
@BeforeEach
private void resetItems() {
itemRepository.deleteAll();
}
@Test
public void saveTest() {
Item item = new Item("kartoffel", Unit.g, 5000);
itemRepository.save(item);
assertTrue(itemRepository.existsById(item.getId()));
}
@Test
public void findByIDTest() {
Item item = new Item("tortillias", Unit.g, 5000);
itemRepository.save(item);
assertEquals(item, itemRepository.findById(item.getId()).get());
}
@Test
public void findByIdNotPresentTest() {
assertFalse(itemRepository.findById(77L).isPresent());
}
@Test
public void findByNameTest(){
Item item = new Item("tortillias", Unit.g, 5000);
itemRepository.save(item);
assertEquals(item, itemRepository.findByName(item.getName()).get());
}
@Test
public void findAllTest() {
List<Item> savedItems = new ArrayList();
savedItems.add( new Item("nachos", Unit.g, 5000));
savedItems.add( new Item("wurst", Unit.g, 5000));
savedItems.add( new Item("schinken", Unit.g, 5000));
savedItems.add( new Item("brokkoli", Unit.g, 5000));
savedItems.add( new Item("eiscreme", Unit.g, 5000));
itemRepository.saveAll(savedItems);
List<Item> foundItems = (List<Item>)itemRepository.findAll();
assertTrue(compListNotId(savedItems, foundItems));
}
@Test
public void deleteTest() {
Item item = new Item("elefantenfuß", Unit.g, 5000);
itemRepository.save(item);
assertEquals(item, itemRepository.findById(item.getId()).get());
itemRepository.delete(item);
assertTrue(itemRepository.findById(item.getId()).isEmpty());
}
@Test
public void updateTest() {
Item item = new Item("schokoküsse", Unit.g, 5000);
itemRepository.save(item);
long itemCount = itemRepository.count();
item.setQuantity(4574);
itemRepository.save(item);
assertEquals(itemCount, itemRepository.count());
assertEquals(4574, itemRepository.findById(item.getId()).get().getQuantity());
}
private boolean compNotId(Item item1, Item item2){
return item1.getName().equals(item2.getName())&&item1.getQuantity()==item2.getQuantity()&&item1.getUnit().equals(item2.getUnit());
}
private boolean compListNotId(List<Item> expected, List<Item> actual){
if (expected.size() != actual.size()){
return false;
}
for (int i = 0; i < expected.size(); i++){
if(!compNotId(expected.get(i), actual.get(i))){
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,16 @@
server:
port: 9000
spring:
datasource:
url: jdbc:h2:mem:whattocook
username: sa
password:
driverClassName: org.h2.Driver
data:
rest:
base-path: /api/v1
logging:
level:
root: DEBUG