Add example project

This commit is contained in:
GuilhermeWerner
2021-09-17 14:39:06 -03:00
parent 226b7856c5
commit 15cf8e5e68
9 changed files with 657 additions and 0 deletions

49
.classpath Normal file
View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="target/generated-sources/annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="ignore_optional_problems" value="true"/>
<attribute name="m2e-apt" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

34
.project Normal file
View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>03ProdutoService</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
<filteredResources>
<filter>
<id>1631728775121</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

18
pom.xml Normal file
View File

@ -0,0 +1,18 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ti2cc</groupId>
<artifactId>03ProdutoService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
</project>

BIN
produto.dat Normal file

Binary file not shown.

View File

@ -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));
}
}

View File

@ -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<Produto> 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<Produto>();
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<Produto> getAll() {
return produtos;
}
private List<Produto> 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();
}
}
}

View File

@ -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());
}
}

View File

@ -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 "<produto>\n" + "\t<id>" + produto.getId() + "</id>\n" + "\t<descricao>" + produto.getDescricao()
+ "</descricao>\n" + "\t<preco>" + produto.getPreco() + "</preco>\n" + "\t<quantidade>"
+ produto.getQuant() + "</quantidade>\n" + "\t<fabricacao>" + produto.getDataFabricacao()
+ "</fabricacao>\n" + "\t<validade>" + produto.getDataValidade() + "</validade>\n" + "</produto>\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("<produtos type=\"array\">");
for (Produto produto : produtoDAO.getAll()) {
returnValue.append("\n<produto>\n" + "\t<id>" + produto.getId() + "</id>\n" + "\t<descricao>"
+ produto.getDescricao() + "</descricao>\n" + "\t<preco>" + produto.getPreco() + "</preco>\n"
+ "\t<quantidade>" + produto.getQuant() + "</quantidade>\n" + "\t<fabricacao>"
+ produto.getDataFabricacao() + "</fabricacao>\n" + "\t<validade>" + produto.getDataValidade()
+ "</validade>\n" + "</produto>\n");
}
returnValue.append("</produtos>");
response.header("Content-Type", "application/xml");
response.header("Content-Encoding", "UTF-8");
return returnValue.toString();
}
}

View File

@ -0,0 +1,186 @@
<html>
<head>
<meta content="text/html; charset = UTF-8" http-equiv="content-type">
<title>Controle de Estoque</title>
</head>
<script type="text/javascript">
function addIdToPath(form_name, base_url) {
var your_form = document.getElementById(form_name);
var id = your_form.elements.namedItem("id").value;
action_src = base_url + id;
your_form.action = action_src;
}
</script>
<body>
<p>
<h1>Controle de Estoque</h1>
</p>
<section class="section--container__responsive">
<section class="section--mainrow__responsive first--section">
<h1 class="generaltext">Inserir Produto</h1>
<form class="form--register" action="http://localhost:6789/produto" method="post" id="form-add">
<p>Descrição:</p>
<input class="input--register" type="text" name="descricao" value="" placeholder="leite, pão...">
<p>Preco:</p>
<input class="input--register" type="text" name="preco" value="">
<p>Quantidade:</p>
<input class="input--register" type="text" name="quantidade" value="">
<p>Data de fabricação:</p>
<input class="input--register" type="text" name="dataFabricacao" value=""
placeholder="2020-04-16T12:00:00...">
<p>Data de validade:</p>
<input class="input--register" type="text" name="dataValidade" value="" placeholder="2020-04-16">
<input type="submit" value="cadastrar" class="input--main__style input--button">
</form>
</section>
</section>
<section class="section--container__responsive">
<section class="section--row__responsive">
<h1 class="generaltext">Detalhar produto</h1>
<form onsubmit="addIdToPath('form-get', 'http://localhost:6789/produto/')" method="get" id="form-get">
<input class="input--down" type="text" id="id" value="" placeholder="id do produto...">
<input type="submit" value="consultar" class="input--button input--consult__style">
</form>
</section>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<section class="section--row__responsive">
<h1 class="generaltext">Remover produto</h1>
<form onsubmit="addIdToPath('form-delete', 'http://localhost:6789/produto/delete/')" method="get"
id="form-delete">
<input class="input--down" type="text" id="id" value="" placeholder="id do produto...">
<input type="submit" value="remover" class="input--remove__style input--button">
</form>
</section>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<section class="section--row__responsive">
<h1 class="generaltext">Listar produtos</h1>
<form action="http://localhost:6789/produto" method="get" id="form-all">
<br><br><br>
<input type="submit" value="todos" class="input--consult__style input--button">
</form>
</section>
</section>
<section class="section--container__responsive" style="visibility: hidden" id="product-result">
<table border="1">
<tr>
<td>Produto id:</td>
<td><span id="id">Sem Resultado</span></td>
</tr>
<tr>
<td>Descricao:</td>
<td><span id="descricao">Sem Resultado</span></td>
</tr>
<tr>
<td>Preco:</td>
<td><span id="preco">Sem Resultado</span></td>
</tr>
<tr>
<td>Quantidade:</td>
<td><span id="quant">Sem Resultado</span></td>
</tr>
<tr>
<td>Data de fabricacao:</td>
<td><span id="dataFabricacao">Sem Resultado</span></td>
</tr>
</table>
</section>
<style>
* {
box-sizing: border-box;
}
body {
background-color: white;
}
.generaltext,
p {
font-family: Arial;
text-align: center;
}
.section--container__responsive {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
border-bottom: dashed;
border-color: gray;
}
.input--down {
display: block;
margin: 0px auto;
margin-bottom: 10px;
}
.input--main__style {
background-color: #00FF00;
}
.input--remove__style {
background-color: red;
}
.input--consult__style {
background-color: darkblue;
}
.input--button {
font-weight: bold;
font-family: Arial;
font-size: medium;
border-color: transparent;
display: block;
margin: 0px auto;
margin-bottom: 10px;
color: white;
}
.input--register {
display: inline;
}
.input--radio {
display: inline;
}
input {
display: block;
border-radius: 7px;
padding: 10px;
border-style: solid;
border-color: lightgray;
color: black;
padding: 10px;
margin-bottom: 10px;
}
.p--radio__display {
display: block;
}
form p {
text-align: initial;
display: inline;
margin-left: 15px;
}
.p--nomargin {
margin-left: 0px;
margin-right: 10px;
}
</style>
</body>
</html>