Subversion Repositories Integrator Subversion

Rev

Rev 106 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

package br.com.ec.controller.managedbean;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.persistence.Transient;
import javax.servlet.ServletContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.context.annotation.Scope;

import br.com.ec.core.exception.NegocioException;
import br.com.ec.core.util.ArquivoUtil;
import br.com.ec.core.util.VerificadorUtil;
import br.com.ec.domain.dto.FotoDTO;
import br.com.ec.domain.model.Produto;
import br.com.ec.domain.shared.ConstantesSEC;
import br.com.ec.web.exception.VerificadorLancamentoException;
import br.com.ec.web.exception.VerificadorLancamentoException.CommandBean;
import br.com.ec.web.message.LancadorMensagem;

@Named
@Scope("view")
public class FotoBean {
       
        private FotoDTO fotoNova;
        private UploadedFile fotoParaUpload;
       
        public FotoDTO getFotoNova() {
                return fotoNova;
        }
        public void setFotoNova(FotoDTO fotoNova) {
                this.fotoNova = fotoNova;
        }
       
        public UploadedFile getFotoParaUpload() {
                return fotoParaUpload;
        }
        public void setFotoParaUpload(UploadedFile fotoParaUpload) {
                this.fotoParaUpload = fotoParaUpload;
        }
       
        public String fotoPadraoProduto(Produto produto) {
                try {
                        if (VerificadorUtil.naoEstaNulo(produto)) {
                                if (VerificadorUtil.naoEstaNuloOuVazio(produto.getCodigo())) {
                                        File foto = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + ".jpg");
                                        if (foto.exists()) {
                                                return getCaminhoPadraoFotos() + produto.getCodigoProdutoPadrao() + ".jpg";
                                        } else {
                                                return getCaminhoPadraoFotos() + "SEM_FOTO.jpg";
                                        }
                                }
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                }
               
                return getCaminhoPadraoFotos() + "SEM_FOTO.jpg";
        }
       
        public String fotoPadraoProdutoComCodigo(String codigo) {
                try {
                        Produto produto = new Produto();
                        produto.setCodigo(codigo);
                        if (VerificadorUtil.naoEstaNuloOuVazio(produto.getCodigo())) {
                                File foto = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + ".jpg");
                                if (foto.exists()) {
                                        return getCaminhoPadraoFotos() + produto.getCodigoProdutoPadrao() + ".jpg";
                                } else {
                                        return getCaminhoPadraoFotos() + "SEM_FOTO.jpg";
                                }
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                }
               
                return getCaminhoPadraoFotos() + "SEM_FOTO.jpg";
        }
       
        @Transient
        public List<String> fotosProdutoComFotoPadrao(Produto produto) {
                List<String> fotos = new ArrayList<String>();
                if (VerificadorUtil.naoEstaNulo(produto)) {
                        if (VerificadorUtil.naoEstaNuloOuVazio(produto.getCodigo())) {
                                File fotoPadrao = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + ".jpg");
                                if (fotoPadrao.exists()) {
                                        fotos.add(getCaminhoPadraoFotos() + produto.getCodigoProdutoPadrao() + ".jpg");
                                }
                                fotos.addAll(fotosProduto(produto));
                                return fotos;
                        }
                }
                return fotos;
        }
       
        @Transient
        public List<String> fotosProduto(Produto produto) {
                List<String> fotos = new ArrayList<String>();
                if (VerificadorUtil.naoEstaNulo(produto)) {
                        if (VerificadorUtil.naoEstaNuloOuVazio(produto.getCodigo())) {
                                File foto = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + "_1.jpg");
                                Integer quantidadeFotos = 1;
                                if (foto.exists()) {
                                        while (foto.exists()) {
                                                fotos.add(getCaminhoPadraoFotos() + produto.getCodigoProdutoPadrao() + "_" + quantidadeFotos + ".jpg");
                                                quantidadeFotos++;
                                                foto = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + "_" + quantidadeFotos + ".jpg");
                                        }
                                }
                                return fotos;
                        }
                }
                return fotos;
        }
       
        public String getCaminhoPadraoFotos() {
                if (ConstantesSEC.TESTE_LOCAL) {
                        return ConstantesSEC.Foto.CAMINHO_PADRAO_LOCAL;
                }
                return ConstantesSEC.Foto.CAMINHO_PADRAO_SERVIDOR;
        }
       
        public String getCaminhoPastaFotos() {
                if (ConstantesSEC.TESTE_LOCAL) {
                        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                        return servletContext.getRealPath("") + File.separator + "fotos" + File.separator;
                }                              
                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                return servletContext.getRealPath("") + File.separator + ".." + File.separator + "fotos" + File.separator;
        }
       
        public void prepararUploadFoto(Produto produto) {
                FotoDTO fotoNova = new FotoDTO();
                fotoNova.setDescricao(produto.getCodigoProdutoPadrao());
                setFotoNova(fotoNova);
        }
       
        public void uploadArquivoPadrao(final FileUploadEvent e) {
        new VerificadorLancamentoException().tratarIhRelancarExcecaoSemLimparEntidade(new CommandBean() {
                        public void execute() {
                                FotoDTO arquivoGerado = gerarArquivo(e.getFile());
                                arquivoGerado.setDescricao(getFotoNova().getDescricao());
                                lancarExcecaoCasoArquivoExcedeuLimite(arquivoGerado);
                                arquivoGerado.compactarImagem();
                                setFotoParaUpload(e.getFile());
                                uploadFisico(arquivoGerado);
                                LancadorMensagem.lancarSucesso("Imagem adicionada com sucesso.");
                        }
                });
    }
       
        public void uploadArquivo(final FileUploadEvent e) {
        new VerificadorLancamentoException().tratarIhRelancarExcecaoSemLimparEntidade(new CommandBean() {
                        public void execute() {
                                FotoDTO arquivoGerado = gerarArquivo(e.getFile());
                                arquivoGerado.setDescricao(gerarNovaDescricao(getFotoNova().getDescricao()));
                                lancarExcecaoCasoArquivoExcedeuLimite(arquivoGerado);
                                arquivoGerado.compactarImagem();
                                setFotoParaUpload(e.getFile());
                                uploadFisico(arquivoGerado);
                                LancadorMensagem.lancarSucesso("Imagem adicionada com sucesso.");
                        }
                });
    }
       
        protected String gerarNovaDescricao(String codigo) {
                Produto produto = new Produto();
                produto.setCodigo(codigo);
                List<String> fotos = fotosProduto(produto);
                Integer proximoCodigo = 1;
                for (String foto : fotos) {
                        if (foto.contains("_" + proximoCodigo)) {
                                proximoCodigo++;
                        }
                }
                return produto.getCodigoProdutoPadrao() + "_" + proximoCodigo.toString();
        }
       
        public void uploadFisico(FotoDTO arquivoGerado) {
                String caminho = getCaminhoPastaFotos() + arquivoGerado.getDescricao() + "." + arquivoGerado.getExtensao();
                FileOutputStream fos;
                try {
                        fos = new FileOutputStream(caminho);
                        fos.write(arquivoGerado.getArquivo());
                        fos.close();
                } catch (Exception e1) {
                        e1.printStackTrace();
                }
        }
       
        private void lancarExcecaoCasoArquivoExcedeuLimite(FotoDTO arquivoGerado) {
                if (arquivoGerado.isExcedeuLimite()) {
                        throw new NegocioException("Arquivo: " + arquivoGerado.getDescricao() + " excedeu o limite de 3000 kbytes. ");
                }
        }
       
        private FotoDTO gerarArquivo(UploadedFile file) {
                FotoDTO arquivo = new FotoDTO();
                arquivo.setArquivo(file.getContents());
                arquivo.setDescricao(file.getFileName());
                arquivo.setExtensao(ArquivoUtil.retornarExtensaoDoArquivo(file.getFileName()));
                return arquivo;
        }
       
        public void excluirFotoPadrao(final Produto produto) {
                try {
                        File fotoParaExcluir = new File(getCaminhoPastaFotos() + produto.getCodigoProdutoPadrao() + ".jpg");
                        if (fotoParaExcluir.exists()) {
                                fotoParaExcluir.delete();
                                LancadorMensagem.lancarSucesso("Imagem excluída com sucesso.");
                        } else {
                                LancadorMensagem.lancarErro("Erro ao excluir imagem");
                        }
                } catch (Exception e1) {
                        LancadorMensagem.lancarErro("Erro ao excluir imagem");
                }
        }
       
        public void excluirFoto(final String foto) {
                try {
                        String codigoFoto = foto.substring(foto.indexOf("fotos/")+6, foto.indexOf("_"));
                        String ordenadorFoto = foto.substring(foto.indexOf("_")+1, foto.indexOf("."));
                        String caminhoFoto = foto.substring(foto.indexOf("fotos/")+6);
                        File fotoParaExcluir = new File(getCaminhoPastaFotos() + caminhoFoto);
                        if (fotoParaExcluir.exists()) {
                                fotoParaExcluir.delete();
                                // REORGANIZAR LISTA
                                Integer proximoCodigo = new Integer(ordenadorFoto);
                                proximoCodigo++;
                                File fotoRenomear = new File(getCaminhoPastaFotos() + codigoFoto + "_" + proximoCodigo + ".jpg");
                                while (fotoRenomear.exists()) {
                                        proximoCodigo--;
                                        File fotoRenomeada = new File(getCaminhoPastaFotos() + codigoFoto + "_" + proximoCodigo + ".jpg");
                                        fotoRenomear.renameTo(fotoRenomeada);
                                        proximoCodigo = proximoCodigo + 2;
                                        fotoRenomear = new File(getCaminhoPastaFotos() + codigoFoto + "_" + proximoCodigo + ".jpg");
                                }
                                LancadorMensagem.lancarSucesso("Imagem excluída com sucesso.");
                        } else {
                                LancadorMensagem.lancarErro("Erro ao excluir imagem");
                        }
                } catch (Exception e1) {
                        LancadorMensagem.lancarErro("Erro ao excluir imagem");
                }
        }
       
        /*********************************/

        private static Integer quantidadeFotosDisponiveis() {
//              ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
//              String caminhoArquivoPadrao = servletContext.getRealPath("") + File.separator + "imagens" + File.separator + "temp" + File.separator;
                ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
                String caminhoArquivoPadrao = servletContext.getRealPath("") + File.separator + "fotos" + File.separator + "SEM_FOTO.jpg";
               
                Integer quantidadeFotos = 0;
//              String caminhoArquivoPadrao = "src/main/resources/fotos/";
                File file = new File(caminhoArquivoPadrao);
                File[] arquivos = file.listFiles();
                for (File fileTmp : arquivos) {
                        quantidadeFotos++;
//                      System.out.println(fileTmp.getName());
                }
                return quantidadeFotos;
        }
       
        public static void main(String[] args) {
                String foto = "espacocase/fotos/010632_1.jpg";
                String caminhoFoto = foto.substring(foto.indexOf("fotos/")+6);
                System.out.println(caminhoFoto);
        }
       
}