Created
March 16, 2018 23:30
-
-
Save anonymous/a9225efcd0d6736ebedd411d388bf8a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.livraria.dao; | |
import java.io.Serializable; | |
import java.util.List; | |
import javax.annotation.PostConstruct; | |
import javax.inject.Inject; | |
import javax.persistence.EntityManager; | |
import br.com.caelum.livraria.modelo.Autor; | |
public class AutorDao implements Serializable { | |
private static final long serialVersionUID = 1L; | |
@Inject | |
EntityManager em; | |
private DAO<Autor> dao; | |
@PostConstruct | |
void init() { | |
this.dao = new DAO<Autor>(em, Autor.class); | |
} | |
public List<Autor> listaTodos() { | |
return this.dao.listaTodos(); | |
} | |
public void adiciona(Autor autor) { | |
this.dao.adiciona(autor); | |
} | |
public void remove(Autor autor) { | |
this.dao.remove(autor); | |
} | |
public Autor buscaPorId(Integer id) { | |
return this.dao.buscaPorId(id); | |
} | |
public void atualiza(Autor autor) { | |
this.dao.atualiza(autor); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8" ?> | |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> | |
<html xmlns="http://www.w3.org/1999/xhtml" | |
xmlns:h="http://xmlns.jcp.org/jsf/html" | |
xmlns:f="http://xmlns.jcp.org/jsf/core" | |
xmlns:p="http://primefaces.org/ui" | |
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"> | |
<ui:composition template="_template.xhtml"> | |
<f:metadata> | |
<f:viewParam name="livroId" value="#{livroBean.livro.id}" /> | |
<f:viewAction action="#{livroBean.carregaPelaId}" if="#{param.livroId != null}" /> | |
</f:metadata> | |
<ui:define name="titulo"> | |
<p:outputPanel>Novo Livro</p:outputPanel> | |
</ui:define> | |
<ui:define name="conteudo"> | |
<h:form id="formLivro"> | |
<p:messages id="messages" /> | |
<p:fieldset legend="Dados do Livro"> | |
<p:panelGrid columns="2"> | |
<p:outputLabel value="Titulo:" for="titulo" /> | |
<p:inputText id="titulo" value="#{livroBean.livro.titulo}" | |
required="true" requiredMessage="Título obrigatório" | |
validatorMessage="Título não pode ser superior a 40"> | |
<f:validateLength maximum="40" /> | |
<f:ajax event="blur" render="messages" /> | |
</p:inputText> | |
<p:outputLabel value="ISBN:" for="isbn" /> | |
<p:inputMask id="isbn" value="#{livroBean.livro.isbn}" | |
mask="999-9-9999999-9-9" validator="#{livroBean.comecaComDigitoUm}"> | |
<f:ajax event="blur" render="messages" /> | |
</p:inputMask> | |
<p:outputLabel value="Preço:" for="preco" /> | |
<p:inputNumber id="preco" symbol="R$ " decimalSeparator="," thousandSeparator="." | |
value="#{livroBean.livro.preco}" /> | |
<p:outputLabel value="Data de Lançamento:" for="dataLancamento" /> | |
<p:calendar id="dataLancamento" value="#{livroBean.livro.dataLancamento.time}" timeZone="America/Sao_Paulo" | |
pattern="dd/MM/yyyy" mask="true" showOn="button" /> | |
<p:outputLabel value="Gênero:" for="genero" /> | |
<p:selectOneMenu value="#{livroBean.livro.genero.id}" id="genero"> | |
<f:selectItem itemLabel="Selecione" itemValue="#{null}"/> | |
<f:selectItems value="#{livroBean.generos}" var="genero" | |
itemLabel="#{genero.nome}" itemValue="#{genero.id}" /> | |
</p:selectOneMenu> | |
</p:panelGrid> | |
</p:fieldset> | |
<p:fieldset legend="Dados do Autor"> | |
<p:panelGrid columns="4"> | |
<p:outputLabel value="Selecione Autor:" for="autor" /> | |
<p:selectOneMenu value="#{livroBean.autorId}" id="autor"> | |
<f:selectItems value="#{livroBean.autores}" var="autor" | |
itemLabel="#{autor.nome}" itemValue="#{autor.id}" /> | |
</p:selectOneMenu> | |
<p:commandButton value="Gravar Autor" action="#{livroBean.gravarAutor}" | |
process="@this autor" update="tabelaAutores"> | |
</p:commandButton> | |
<p:commandLink value="ou cadastrar novo autor" action="#{livroBean.formAutor}" immediate="true" | |
update="@all"/> | |
</p:panelGrid> | |
<p:dataTable value="#{livroBean.autoresDoLivro}" var="autor" id="tabelaAutores" emptyMessage="Nenhum autor"> | |
<p:column> | |
<h:outputText value="#{autor.nome}" /> | |
</p:column> | |
<p:column> | |
<p:commandLink value="X" action="#{livroBean.removerAutorDoLivro(autor)}" update="tabelaAutores" process="@this"/> | |
</p:column> | |
</p:dataTable> | |
</p:fieldset> | |
<p:commandButton value="Gravar" action="#{livroBean.gravar}" process="@form" update="@form :formTabelaLivros:tabelaLivros" /> | |
| |
<p:commandButton value="Limpar" action="#{livroBean.limpar}" update="@form" disabled="#{livroBean.livro.id == null}" /> | |
</h:form> | |
<br /> | |
<br /> | |
<h:form id="formTabelaLivros"> | |
<p:dataTable value="#{livroBean.livros}" var="livro" id="tabelaLivros" rows="5" paginator="true" widgetVar="tabelaLivros"> | |
<f:facet name="header">Listagem de Livros</f:facet> | |
<p:column headerText="Título" sortBy="#{livro.titulo}" filterBy="#{livro.titulo}" filterMatchMode="startsWith"> | |
<h:outputText value="#{livro.titulo}" /> | |
</p:column> | |
<p:column headerText="ISBN" sortBy="#{livro.isbn}" filterBy="#{livro.titulo}" filterMatchMode="contains"> | |
<h:outputText value="#{livro.isbn}" /> | |
</p:column> | |
<p:column headerText="Preço" sortBy="#{livro.preco}" filterBy="#{livro.preco}" filterFunction="#{livroBean.precoEhMenor}"> | |
<h:outputText value="#{livro.preco}"> | |
<f:convertNumber type="currency" pattern="R$ #0.00" | |
currencySymbol="R$" locale="pt_BR" /> | |
</h:outputText> | |
</p:column> | |
<p:column headerText="Data" sortBy="#{livro.dataLancamento.time}" filterBy="#{livro.dataLancamento.time}" filterMatchMode="contains"> | |
<h:outputText value="#{livro.dataLancamento.time}"> | |
<f:convertDateTime pattern="dd/MM/yyyy" | |
timeZone="America/Sao_Paulo" /> | |
</h:outputText> | |
</p:column> | |
<p:column headerText="Gênero" sortBy="#{livro.genero.nome}" filterBy="#{livro.genero.nome}" filterMatchMode="startsWith"> | |
<f:facet name="filter"> | |
<p:selectOneMenu onchange="PF('tabelaLivros').filter()"> | |
<f:selectItem itemLabel="Selecione..." itemValue="#{null}" noSelectionOption="true" /> | |
<f:selectItems value="#{livroBean.generos}" /> | |
</p:selectOneMenu> | |
</f:facet> | |
<h:outputText value="#{livro.genero.nome}" /> | |
</p:column> | |
<p:column headerText="Alterar"> | |
<p:commandButton update=":formLivro" process="@this" value="alterar" actionListener="#{livroBean.carregar(livro)}" icon="fa fa-fw fa-edit" /> | |
</p:column> | |
<p:column headerText="Remover"> | |
<p:commandButton update="@form" process="@this" value="remover" actionListener="#{livroBean.remover(livro)}" icon="fa fa-fw fa-remove" /> | |
</p:column> | |
</p:dataTable> | |
</h:form> | |
</ui:define> | |
</ui:composition> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.livraria.bean; | |
import java.io.Serializable; | |
import java.util.List; | |
import java.util.Locale; | |
import javax.annotation.PostConstruct; | |
import javax.faces.application.FacesMessage; | |
import javax.faces.bean.ViewScoped; | |
import javax.faces.component.UIComponent; | |
import javax.faces.context.FacesContext; | |
import javax.faces.validator.ValidatorException; | |
import javax.inject.Inject; | |
import javax.inject.Named; | |
import br.com.caelum.livraria.dao.AutorDao; | |
import br.com.caelum.livraria.dao.GeneroDao; | |
import br.com.caelum.livraria.dao.LivroDao; | |
import br.com.caelum.livraria.modelo.Autor; | |
import br.com.caelum.livraria.modelo.Genero; | |
import br.com.caelum.livraria.modelo.Livro; | |
import br.com.caelum.livraria.modelo.LivroDataModel; | |
@Named | |
@ViewScoped | |
public class LivroBean implements Serializable { | |
private static final long serialVersionUID = 1L; | |
private Livro livro = new Livro(); | |
private Integer autorId; | |
private List<Livro> livros; | |
@Inject | |
private LivroDao livroDao; | |
@Inject | |
private AutorDao autorDao; | |
@Inject | |
private GeneroDao generoDao; | |
@Inject | |
private LivroDataModel livroDataModel; | |
private List<Genero> generos; | |
public void setAutorId(Integer autorId) { | |
this.autorId = autorId; | |
} | |
public Integer getAutorId() { | |
return autorId; | |
} | |
public Livro getLivro() { | |
return livro; | |
} | |
public List<Livro> getLivros() { | |
if (this.livros == null) { | |
this.livros = this.livroDao.listaTodos(); | |
} | |
return livros; | |
} | |
public List<Autor> getAutores() { | |
return this.autorDao.listaTodos(); | |
} | |
public int getQtdTotalLivros() { | |
return this.autorDao.listaTodos().size(); | |
} | |
public List<Autor> getAutoresDoLivro() { | |
return this.livro.getAutores(); | |
} | |
public List<Genero> getGeneros() { | |
if (generos == null) { | |
generos = this.generoDao.listaTodos(); | |
} | |
return generos; | |
} | |
public void gravarAutor() { | |
Autor autor = autorDao.buscaPorId(this.autorId); | |
this.livro.adicionaAutor(autor); | |
System.out.println("Escrito por: " + autor.getNome()); | |
} | |
public LivroDataModel getLivroDataModel() { | |
return livroDataModel; | |
} | |
public void setLivro(Livro livro) { | |
this.livro = livro; | |
} | |
public void gravar() { | |
System.out.println("Gravando livro " + this.livro.getTitulo()); | |
if (livro.getAutores().isEmpty()) { | |
FacesContext.getCurrentInstance().addMessage("autor", | |
new FacesMessage("Livro deve ter pelo menos um Autor.")); | |
return; | |
} | |
if (this.livro.getId() == null) { | |
livroDao.adiciona(this.livro); | |
} else { | |
livroDao.atualiza(this.livro); | |
} | |
this.livros.add(this.livro); | |
this.livro = new Livro(); | |
} | |
public void carregar(Livro livro) { | |
System.out.println("Carregando livro " + livro.getTitulo()); | |
this.livro = livro; | |
} | |
public void remover(Livro livro) { | |
this.livros.remove(livro); | |
this.livroDao.remove(livro); | |
} | |
public void removerAutorDoLivro(Autor autor) { | |
this.livro.removeAutor(autor); | |
} | |
public String formAutor() { | |
System.out.println("Chamanda do formulário do Autor."); | |
return "autor?faces-redirect=true"; | |
} | |
public void comecaComDigitoUm(FacesContext fc, UIComponent component, Object value) throws ValidatorException { | |
String valor = value.toString(); | |
if (!valor.startsWith("1")) { | |
throw new ValidatorException(new FacesMessage("ISBN deveria começar com 1")); | |
} | |
} | |
public String cadastroAutor(Integer id) { | |
System.out.println("Chamanda do formulário do Autor."); | |
String url = "autor?faces-redirect=true&autorId=" + id; | |
if (this.livro.getId() != null) { | |
url += "&livroId=" + this.livro.getId(); | |
} | |
return url; | |
} | |
public void carregaPelaId() { | |
System.out.println("Carregando livro pelo id..."); | |
this.livro = livroDao.buscaPorId(this.livro.getId()); | |
if (this.livro == null) { | |
this.livro = new Livro(); | |
} | |
} | |
public void limpar() { | |
this.livro = new Livro(); | |
} | |
public boolean precoEhMenor(Object valorColuna, Object filtroDigitado, Locale locale) { // java.util.Locale | |
// tirando espaços do filtro | |
String textoDigitado = (filtroDigitado == null) ? null : filtroDigitado.toString().trim(); | |
System.out.println("Filtrando pelo " + textoDigitado + ", Valor do elemento: " + valorColuna); | |
// o filtro é nulo ou vazio? | |
if (textoDigitado == null || textoDigitado.equals("")) { | |
return true; | |
} | |
// elemento da tabela é nulo? | |
if (valorColuna == null) { | |
return false; | |
} | |
try { | |
// fazendo o parsing do filtro para converter para Double | |
Double precoDigitado = Double.valueOf(textoDigitado); | |
Double precoColuna = (Double) valorColuna; | |
// comparando os valores, compareTo devolve um valor negativo se o | |
// value é menor do que o filtro | |
return precoColuna.compareTo(precoDigitado) < 0; | |
} catch (NumberFormatException e) { | |
// usuario nao digitou um numero | |
return false; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.livraria.dao; | |
import java.io.Serializable; | |
import java.util.List; | |
import javax.annotation.PostConstruct; | |
import javax.inject.Inject; | |
import javax.persistence.EntityManager; | |
import br.com.caelum.livraria.modelo.Livro; | |
public class LivroDao implements Serializable { | |
private static final long serialVersionUID = 1L; | |
@Inject | |
EntityManager em; | |
private DAO<Livro> dao; | |
@PostConstruct | |
void init() { | |
this.dao = new DAO<Livro>(this.em, Livro.class); | |
} | |
public void adiciona(Livro t) { | |
dao.adiciona(t); | |
} | |
public void remove(Livro t) { | |
dao.remove(t); | |
} | |
public void atualiza(Livro t) { | |
dao.atualiza(t); | |
} | |
public List<Livro> listaTodos() { | |
return dao.listaTodos(); | |
} | |
public Livro buscaPorId(Integer id) { | |
return dao.buscaPorId(id); | |
} | |
public int contaTodos() { | |
return dao.contaTodos(); | |
} | |
public List<Livro> listaTodosPaginada(int firstResult, int maxResults, String coluna, String valor) { | |
return dao.listaTodosPaginada(firstResult, maxResults, coluna, valor); | |
} | |
public int quantidadeDeElementos() { | |
return dao.quantidadeDeElementos(); | |
} | |
public int quantidadeDeElementosPorAtributo(String atributo, Object valor) { | |
return dao.quantidadeDeElementosPorAtributo(atributo, valor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment