From 15cf8e5e688b0bcdf4dd4760d50c71837d2a8358 Mon Sep 17 00:00:00 2001 From: GuilhermeWerner <26710260+GuilhermeWerner@users.noreply.github.com> Date: Fri, 17 Sep 2021 14:39:06 -0300 Subject: [PATCH] Add example project --- .classpath | 49 ++++++ .project | 34 ++++ pom.xml | 18 +++ produto.dat | Bin 0 -> 558 bytes src/main/java/app/Aplicacao.java | 23 +++ src/main/java/dao/ProdutoDAO.java | 123 ++++++++++++++ src/main/java/model/Produto.java | 111 +++++++++++++ src/main/java/service/ProdutoService.java | 113 +++++++++++++ src/main/resources/formulario.html | 186 ++++++++++++++++++++++ 9 files changed, 657 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 pom.xml create mode 100644 produto.dat create mode 100644 src/main/java/app/Aplicacao.java create mode 100644 src/main/java/dao/ProdutoDAO.java create mode 100644 src/main/java/model/Produto.java create mode 100644 src/main/java/service/ProdutoService.java create mode 100644 src/main/resources/formulario.html diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..0d917bc --- /dev/null +++ b/.classpath @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..b6c006a --- /dev/null +++ b/.project @@ -0,0 +1,34 @@ + + + 03ProdutoService + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + + + 1631728775121 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..05b24bb --- /dev/null +++ b/pom.xml @@ -0,0 +1,18 @@ + + 4.0.0 + com.ti2cc + 03ProdutoService + 0.0.1-SNAPSHOT + + + com.sparkjava + spark-core + 2.9.3 + + + org.slf4j + slf4j-simple + 1.7.21 + + + diff --git a/produto.dat b/produto.dat new file mode 100644 index 0000000000000000000000000000000000000000..2f7950939ef34ff573dc980c6763f037bb044f89 GIT binary patch literal 558 zcmZwD!Aiq07zglgTeEJm4iOc^OA);3ir{UR&5hxph%njB!?!kc8C|nw*;YJw@)djn zuY%ywliR9retcKL zR$5fWiY}cv5vaJ0B;#Y?Ssf`@;8nwss+OrG{WhcG(TkPn#Y%^Y+sm7$-M!Pt5!YC-Bk@T+A5t-c-uuPZ>&D5o^|&gT`NwwrPMQ&s r`T0-0rT@f2GZeAkWkH{t?TL@(8TAC3hh_tNR0LF-9h}aX7x3U06yT1T literal 0 HcmV?d00001 diff --git a/src/main/java/app/Aplicacao.java b/src/main/java/app/Aplicacao.java new file mode 100644 index 0000000..37e3acb --- /dev/null +++ b/src/main/java/app/Aplicacao.java @@ -0,0 +1,23 @@ +package app; + +import static spark.Spark.*; + +import service.ProdutoService; + +public class Aplicacao { + private static ProdutoService produtoService = new ProdutoService(); + + public static void main(String[] args) { + port(6789); + + post("/produto", (request, response) -> produtoService.add(request, response)); + + get("/produto/:id", (request, response) -> produtoService.get(request, response)); + + get("/produto/update/:id", (request, response) -> produtoService.update(request, response)); + + get("/produto/delete/:id", (request, response) -> produtoService.remove(request, response)); + + get("/produto", (request, response) -> produtoService.getAll(request, response)); + } +} diff --git a/src/main/java/dao/ProdutoDAO.java b/src/main/java/dao/ProdutoDAO.java new file mode 100644 index 0000000..e1a237f --- /dev/null +++ b/src/main/java/dao/ProdutoDAO.java @@ -0,0 +1,123 @@ +package dao; + +import model.Produto; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.List; + +public class ProdutoDAO { + private List produtos; + private int maxId = 0; + + private File file; + private FileOutputStream fos; + private ObjectOutputStream outputFile; + + public int getMaxId() { + return maxId; + } + + public ProdutoDAO(String filename) throws IOException { + file = new File(filename); + produtos = new ArrayList(); + if (file.exists()) { + readFromFile(); + } + + } + + public void add(Produto produto) { + try { + produtos.add(produto); + this.maxId = (produto.getId() > this.maxId) ? produto.getId() : this.maxId; + this.saveToFile(); + } catch (Exception e) { + System.out.println("ERRO ao gravar o produto '" + produto.getDescricao() + "' no disco!"); + } + } + + public Produto get(int id) { + for (Produto produto : produtos) { + if (id == produto.getId()) { + return produto; + } + } + return null; + } + + public void update(Produto p) { + int index = produtos.indexOf(p); + if (index != -1) { + produtos.set(index, p); + this.saveToFile(); + } + } + + public void remove(Produto p) { + int index = produtos.indexOf(p); + if (index != -1) { + produtos.remove(index); + this.saveToFile(); + } + } + + public List getAll() { + return produtos; + } + + private List readFromFile() { + produtos.clear(); + Produto produto = null; + try (FileInputStream fis = new FileInputStream(file); + ObjectInputStream inputFile = new ObjectInputStream(fis)) { + + while (fis.available() > 0) { + produto = (Produto) inputFile.readObject(); + produtos.add(produto); + maxId = (produto.getId() > maxId) ? produto.getId() : maxId; + } + } catch (Exception e) { + System.out.println("ERRO ao gravar produto no disco!"); + e.printStackTrace(); + } + return produtos; + } + + private void saveToFile() { + try { + fos = new FileOutputStream(file, false); + outputFile = new ObjectOutputStream(fos); + + for (Produto produto : produtos) { + outputFile.writeObject(produto); + } + outputFile.flush(); + this.close(); + } catch (Exception e) { + System.out.println("ERRO ao gravar produto no disco!"); + e.printStackTrace(); + } + } + + private void close() throws IOException { + outputFile.close(); + fos.close(); + } + + @Override + protected void finalize() throws Throwable { + try { + this.saveToFile(); + this.close(); + } catch (Exception e) { + System.out.println("ERRO ao salvar a base de dados no disco!"); + e.printStackTrace(); + } + } +} diff --git a/src/main/java/model/Produto.java b/src/main/java/model/Produto.java new file mode 100644 index 0000000..286a324 --- /dev/null +++ b/src/main/java/model/Produto.java @@ -0,0 +1,111 @@ +package model; + +import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class Produto implements Serializable { + private static final long serialVersionUID = 1L; + public static final String DESCRICAO_PADRAO = "Novo Produto"; + public static final int MAX_ESTOQUE = 1000; + private int id; + private String descricao; + private float preco; + private int quantidade; + private LocalDateTime dataFabricacao; + private LocalDate dataValidade; + + public Produto() { + id = -1; + descricao = DESCRICAO_PADRAO; + preco = 0.01F; + quantidade = 0; + dataFabricacao = LocalDateTime.now(); + dataValidade = LocalDate.now().plusMonths(6); // o default é uma validade de 6 meses. + } + + public Produto(int id, String descricao, float preco, int quantidade, LocalDateTime fabricacao, LocalDate v) { + setId(id); + setDescricao(descricao); + setPreco(preco); + setQuant(quantidade); + setDataFabricacao(fabricacao); + setDataValidade(v); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + if (descricao.length() >= 3) + this.descricao = descricao; + } + + public float getPreco() { + return preco; + } + + public void setPreco(float preco) { + if (preco > 0) + this.preco = preco; + } + + public int getQuant() { + return quantidade; + } + + public void setQuant(int quantidade) { + if (quantidade >= 0 && quantidade <= MAX_ESTOQUE) + this.quantidade = quantidade; + } + + public LocalDate getDataValidade() { + return dataValidade; + } + + public LocalDateTime getDataFabricacao() { + return dataFabricacao; + } + + public void setDataFabricacao(LocalDateTime dataFabricacao) { + // Pega a Data Atual + LocalDateTime agora = LocalDateTime.now(); + // Garante que a data de fabricação não pode ser futura + if (agora.compareTo(dataFabricacao) >= 0) + this.dataFabricacao = dataFabricacao; + } + + public void setDataValidade(LocalDate dataValidade) { + // a data de fabricação deve ser anterior é data de validade. + if (getDataFabricacao().isBefore(dataValidade.atStartOfDay())) + this.dataValidade = dataValidade; + } + + public boolean emValidade() { + return LocalDateTime.now().isBefore(this.getDataValidade().atTime(23, 59)); + } + + /** + * Método sobreposto da classe Object. É executado quando um objeto precisa ser + * exibido na forma de String. + */ + @Override + public String toString() { + return "Produto: " + descricao + " Preço: R$" + preco + " Quant.: " + quantidade + " Fabricação: " + + dataFabricacao + " Data de Validade: " + dataValidade; + } + + @Override + public boolean equals(Object obj) { + return (this.getId() == ((Produto) obj).getId()); + } +} diff --git a/src/main/java/service/ProdutoService.java b/src/main/java/service/ProdutoService.java new file mode 100644 index 0000000..29c1bc7 --- /dev/null +++ b/src/main/java/service/ProdutoService.java @@ -0,0 +1,113 @@ +package service; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; + +import dao.ProdutoDAO; +import model.Produto; +import spark.Request; +import spark.Response; + +public class ProdutoService { + private ProdutoDAO produtoDAO; + + public ProdutoService() { + try { + produtoDAO = new ProdutoDAO("produto.dat"); + } catch (IOException e) { + System.out.println(e.getMessage()); + } + } + + public Object add(Request request, Response response) { + String descricao = request.queryParams("descricao"); + float preco = Float.parseFloat(request.queryParams("preco")); + int quantidade = Integer.parseInt(request.queryParams("quantidade")); + LocalDateTime dataFabricacao = LocalDateTime.parse(request.queryParams("dataFabricacao")); + LocalDate dataValidade = LocalDate.parse(request.queryParams("dataValidade")); + + int id = produtoDAO.getMaxId() + 1; + + Produto produto = new Produto(id, descricao, preco, quantidade, dataFabricacao, dataValidade); + + produtoDAO.add(produto); + + response.status(201); // 201 Created + return id; + } + + public Object get(Request request, Response response) { + int id = Integer.parseInt(request.params(":id")); + + Produto produto = (Produto) produtoDAO.get(id); + + if (produto != null) { + response.header("Content-Type", "application/xml"); + response.header("Content-Encoding", "UTF-8"); + + return "\n" + "\t" + produto.getId() + "\n" + "\t" + produto.getDescricao() + + "\n" + "\t" + produto.getPreco() + "\n" + "\t" + + produto.getQuant() + "\n" + "\t" + produto.getDataFabricacao() + + "\n" + "\t" + produto.getDataValidade() + "\n" + "\n"; + } else { + response.status(404); // 404 Not found + return "Produto " + id + " não encontrado."; + } + + } + + public Object update(Request request, Response response) { + int id = Integer.parseInt(request.params(":id")); + + Produto produto = (Produto) produtoDAO.get(id); + + if (produto != null) { + produto.setDescricao(request.queryParams("descricao")); + produto.setPreco(Float.parseFloat(request.queryParams("preco"))); + produto.setQuant(Integer.parseInt(request.queryParams("quantidade"))); + produto.setDataFabricacao(LocalDateTime.parse(request.queryParams("dataFabricacao"))); + produto.setDataValidade(LocalDate.parse(request.queryParams("dataValidade"))); + + produtoDAO.update(produto); + + return id; + } else { + response.status(404); // 404 Not found + return "Produto não encontrado."; + } + + } + + public Object remove(Request request, Response response) { + int id = Integer.parseInt(request.params(":id")); + + Produto produto = (Produto) produtoDAO.get(id); + + if (produto != null) { + + produtoDAO.remove(produto); + + response.status(200); // success + return id; + } else { + response.status(404); // 404 Not found + return "Produto não encontrado."; + } + } + + public Object getAll(Request request, Response response) { + StringBuffer returnValue = new StringBuffer(""); + for (Produto produto : produtoDAO.getAll()) { + returnValue.append("\n\n" + "\t" + produto.getId() + "\n" + "\t" + + produto.getDescricao() + "\n" + "\t" + produto.getPreco() + "\n" + + "\t" + produto.getQuant() + "\n" + "\t" + + produto.getDataFabricacao() + "\n" + "\t" + produto.getDataValidade() + + "\n" + "\n"); + } + returnValue.append(""); + response.header("Content-Type", "application/xml"); + response.header("Content-Encoding", "UTF-8"); + return returnValue.toString(); + } +} diff --git a/src/main/resources/formulario.html b/src/main/resources/formulario.html new file mode 100644 index 0000000..c23c249 --- /dev/null +++ b/src/main/resources/formulario.html @@ -0,0 +1,186 @@ + + + + + + Controle de Estoque + + + + + +

+

Controle de Estoque

+

+
+
+

Inserir Produto

+
+

Descrição:

+ +

Preco:

+ +

Quantidade:

+ +

Data de fabricação:

+ +

Data de validade:

+ + +
+
+
+
+
+

Detalhar produto

+
+ + +
+
+ +                      + +
+

Remover produto

+
+ + +
+
+ +                      + +
+

Listar produtos

+
+


+ +
+
+
+ + + + + + +