Locking system after image upload

Asked

Viewed 142 times

0

People in my system, I upload a certain image, the image is saved in a directory and then saved the product in the bank, until then certain td, the problem is that after saving the product the system hangs, in the server log does not present any error, I am using wildfly, If I click to call another page the server generates the query log correctly but does not display. How to fix this problem?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.ProdutoDAO;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.el.ELResolver;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import model.Produto;
import org.primefaces.event.FileUploadEvent;
import util.UploadArquivo;

/**
 *
 * @author Nicoletti
 */
@ManagedBean
@ViewScoped
public class ProdutoBean implements Serializable {

    protected String id;
    private static final long serialVersionUID = 1L;

    private Produto prod = new Produto();
    private final ProdutoDAO prodDAO = new ProdutoDAO();

    public void cadastrar() throws IOException {

        if (prod.getIdProduto() != null) {
            prodDAO.atualizar(prod);
        } else {
            FacesContext c = FacesContext.getCurrentInstance();
            ELResolver r = c.getApplication().getELResolver();
            EmpresaBean empresaBean = (EmpresaBean) r.getValue(c.getELContext(), null, "empresaBean");
            prod.setEmpresa(empresaBean.getEm());
            Date data = new Date();
            prod.setDataCadastro(data);
            prodDAO.cadastrar(prod);
        }
        this.prod = new Produto();
        FacesContext.getCurrentInstance().getExternalContext().redirect("listaproduto.xhtml");

    }

    public void limparCampos() {
        this.prod = null;
        this.prod = new Produto();
    }

    public void carregar(Produto p) throws IOException {
        this.prod = p;
        FacesContext.getCurrentInstance().getExternalContext().redirect("admproduto.xhtml?id="+p.getIdProduto());
}

    public void carregar() {
        if (id != null && prod.getIdProduto() == null) {
            prod = prodDAO.carregar(Long.parseLong(id));
        }
    }

    public Produto getProd() {
        return prod;
    }

    public void setProd(Produto prod) {
        this.prod = prod;
    }

    public List<Produto> listar(String s) {
        List<Produto> results = new ArrayList<>();
        new ProdutoDAO().listar(s).stream().forEach((p) -> {
            results.add(p);
        });
        return results;

    }

    public void upload(FileUploadEvent event) {

        if (event != null) {
            try {
                Date data = new Date();
                prod.setImagem(data.getTime() + ".png");
                UploadArquivo up = new UploadArquivo();
                up.copyFile(prod.getImagem(), event.getFile().getInputstream());
            } catch (Exception ex) {
                System.out.println("Erro ao fazer upload: " + ex.getMessage());
            }
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public ProdutoBean() {
    }

}


<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
            template="./../template/template.xhtml"
            xmlns:p="http://primefaces.org/ui"
            xmlns:h="http://xmlns.jcp.org/jsf/html"
            xmlns:f="http://xmlns.jcp.org/jsf/core">

<ui:define name="content">
    <p:panel class="semBorda">
        <f:metadata>
            <f:viewParam name="id" value="#{produtoBean.id}" />
            <f:event type="preRenderView" listener="#{produtoBean.carregar}" />
        </f:metadata>
        <h:outputText value="Cadastro de Produto"></h:outputText>
        <p:separator/>
        <h:form>
            <p:messages></p:messages>
            <p:panelGrid columns="2">
                <p:panelGrid columns="2">

                    <p:outputLabel value="ID: "></p:outputLabel>
                    <p:outputLabel value="#{produtoBean.prod.idProduto}"></p:outputLabel>

                    <p:outputLabel value="Nome Produto: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.nomeProduto}"></p:inputText>

                    <p:outputLabel value="Observação Produto: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.obsProduto}"></p:inputText>

                    <p:outputLabel value="Código de Barras: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.codigoBarra}"></p:inputText>

                    <p:outputLabel value="Valor Compra: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.vlrCompra}"></p:inputText>

                    <p:outputLabel value="Valor Venda: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.vlrVenda}"></p:inputText>

                    <p:outputLabel value="Desconto Produto: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.descontoProduto}"></p:inputText>

                    <p:outputLabel value="Validade Produto: "></p:outputLabel>
                    <p:calendar value="#{produtoBean.prod.validadeProduto}"></p:calendar>

                    <p:outputLabel value="Status Web: "></p:outputLabel>
                    <p:selectOneRadio value="#{produtoBean.prod.statusWeb}">
                        <f:selectItem itemLabel="Ativado" itemValue="true"></f:selectItem>
                        <f:selectItem itemLabel="Desativado" itemValue="false"></f:selectItem>
                    </p:selectOneRadio>

                    <p:outputLabel value="Lote: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.loteProduto}"></p:inputText>

                    <p:outputLabel value="Estoque Mínimo: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.estoqueMin}"></p:inputText>

                    <p:outputLabel value="Quantidade Estoque: "></p:outputLabel>
                    <p:inputText value="#{produtoBean.prod.quantEstoque}"></p:inputText>

                </p:panelGrid>
                <p:panelGrid columns="2">
                    <p:outputLabel value="Fornecedor: "></p:outputLabel>
                    <p:selectOneListbox converter="fornecedorConverter" value="#{produtoBean.prod.fornecedor}">
                        <f:selectItems value="#{fornecedorBean.lista()}"
                                       var="fornecedor"
                                       itemLabel="#{fornecedor.nome}"
                                       itemValue="#{fornecedor}"
                                       >
                        </f:selectItems>
                    </p:selectOneListbox>

                    <p:outputLabel value="Formúla:  "></p:outputLabel>
                    <p:inputTextarea value="#{produtoBean.prod.formula}"></p:inputTextarea>

                    <p:outputLabel value="Laboratório: "></p:outputLabel>
                    <p:selectOneListbox converter="laboratorioConverter" value="#{produtoBean.prod.laboratorio}">
                        <f:selectItems value="#{laboratorioBean.lista()}"
                                       var="laboratorio"
                                       itemLabel="#{laboratorio.nomeLaboratorio}"
                                       itemValue="#{laboratorio}"
                                       >
                        </f:selectItems>
                    </p:selectOneListbox>

                    <p:outputLabel value="Grupo: "></p:outputLabel>
                    <p:selectOneListbox converter="grupoConverter" value="#{produtoBean.prod.grupo}">
                        <f:selectItems value="#{grupoBean.lista()}"
                                       var="grupo"
                                       itemLabel="#{grupo.nomeGrupo}"
                                       itemValue="#{grupo}"
                                       >
                        </f:selectItems>
                    </p:selectOneListbox>

                    <p:outputLabel value="Selecione uma imagem: "></p:outputLabel>
                    <p:fileUpload id="upload" update="imagem"
                                  fileUploadListener="#{produtoBean.upload}" auto="true"></p:fileUpload>
                    <p:outputLabel value="Imagem: "></p:outputLabel>
                    <p:graphicImage cache="false" id="imagem" height="50px" width="50px" value="../imagens/#{produtoBean.prod.imagem}"></p:graphicImage>
                    <p:commandButton action="#{produtoBean.cadastrar}"  value="Gravar" ajax="false"></p:commandButton>

                </p:panelGrid>
            </p:panelGrid>
        </h:form>
    </p:panel>
</ui:define>

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import com.mchange.v2.lang.StringUtils;
import controller.EmpresaBean;
import java.util.List;
import javax.el.ELResolver;
import javax.faces.context.FacesContext;
import model.Produto;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import util.Filtro;
import util.HibernateUtil;

/**
 *
 * @author Nicoletti
 */
public class ProdutoDAO {

private Session sessao;
private Transaction trans;
private List<Produto> list;

public void cadastrar(Produto p) {
    sessao = HibernateUtil.getSession();
    trans = sessao.beginTransaction();
    try {

        sessao.save(p);
        trans.commit();
    } catch (HibernateException e) {
        System.out.println("Erro ao gravar: " + e.getMessage());
    }finally {
       HibernateUtil.clearSession();
    }
}

public void atualizar(Produto p) {
    sessao = HibernateUtil.getSession();
    trans = sessao.beginTransaction();
    try {

        sessao.merge(p);
        trans.commit();
    } catch (HibernateException e) {
        System.out.println("Erro ao atualizar: " + e.getMessage());
    }finally {
       HibernateUtil.clearSession();
    }
}

public List<Produto> listar() {
    sessao = HibernateUtil.getSession();
    Criteria cri = sessao.createCriteria(Produto.class);
    FacesContext c = FacesContext.getCurrentInstance();
    ELResolver r = c.getApplication().getELResolver();
    EmpresaBean empresaBean = (EmpresaBean) r.getValue(c.getELContext(), null, "empresaBean");
    cri.add(Restrictions.eq("empresa", empresaBean.getEm()));
    this.list = cri.list();
    return list;
}

public List<Produto> listar(String s) {
    sessao = HibernateUtil.getSession();
    Criteria cri = sessao.createCriteria(Produto.class);
    FacesContext c = FacesContext.getCurrentInstance();
    ELResolver r = c.getApplication().getELResolver();
    EmpresaBean empresaBean = (EmpresaBean) r.getValue(c.getELContext(), null, "empresaBean");
    cri.add(Restrictions.eq("empresa", empresaBean.getEm()));
    cri.addOrder(Order.asc("nomeProduto"));
    cri.add(Restrictions.like("nomeProduto", s + "%"));
    return cri.list();

}

public List<Produto> filtrados(Filtro filtro) {
    try {
        Criteria criteria = criarCriteriaParaFiltro(filtro);

        criteria.setFirstResult(filtro.getPrimeiroRegistro());
        criteria.setMaxResults(filtro.getQuantidadeRegistros());

        if (filtro.isAscendente() && filtro.getPropriedadeOrdenacao() != null) {
            criteria.addOrder(Order.asc(filtro.getPropriedadeOrdenacao()));
        } else if (filtro.getPropriedadeOrdenacao() != null) {
            criteria.addOrder(Order.desc(filtro.getPropriedadeOrdenacao()));
        }
        return criteria.list();
    } catch (Exception ex) {
        System.out.println("Erro: " + ex.getMessage());
        return null;
    } finally {
       HibernateUtil.closeSession();
    }

}

public int quantidadeFiltrados(Filtro filtro) {
    try {
        Criteria criteria = criarCriteriaParaFiltro(filtro);

        criteria.setProjection(Projections.rowCount());

        return ((Number) criteria.uniqueResult()).intValue();
    } catch (Exception ex) {
        System.out.println("Erro: " + ex.getMessage());
        return 0;
    }
}

private Criteria criarCriteriaParaFiltro(Filtro filtro) {
    try {
        sessao = HibernateUtil.getSession();
        Criteria criteria = sessao.createCriteria(Produto.class);
        FacesContext c = FacesContext.getCurrentInstance();
        ELResolver r = c.getApplication().getELResolver();
        EmpresaBean empresaBean = (EmpresaBean) r.getValue(c.getELContext(), null, "empresaBean");
        criteria.add(Restrictions.eq("empresa", empresaBean.getEm()));

        if (StringUtils.nonEmptyString(filtro.getDescricao())) {
            criteria.add(Restrictions.ilike("nomeProduto", filtro.getDescricao(), MatchMode.ANYWHERE));
        }
        return criteria;
    } catch (Exception ex) {
        System.out.println("Erro: " + ex.getMessage());
        return null;
    }
}

public Produto carregar(Long i) {
    sessao = HibernateUtil.getSession();
    Produto em = (Produto) sessao.load(Produto.class, i);
    return em;
}
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

public class UploadArquivo {

public String getRealPath() {
    FacesContext aFacesContext = FacesContext.getCurrentInstance();
    ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();

    return context.getRealPath("/");
}

public void copyFile(String fileName, InputStream in) {
    try {
        File file = new File(getRealPath() + "\\imagens\\");
        file.mkdirs();
        try (
            OutputStream out = new FileOutputStream(new File(getRealPath()+"\\imagens\\" + fileName))) 
        {
            int read = 0;
            byte[] bytes = new byte[1024];
            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            in.close();
            out.flush();
        }
        System.out.println("Arquivo criado.");
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

}
  • When it hangs? on the registration page or when it opens the.xhtml product listing page?

  • After registering, I can put to redirect to any page that it will load the page normally but after that the system no longer navigates, and the server log shows that queries are being made.

  • Saving the product without uploading the image makes the system crash? Just to make sure that the problem only occurs when the image is uploaded.

  • Sorry for the delay, but the post was solved, the problem was that it was not closing the connection when listing the products.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.