5
respostas

Erro no Lista.xhtml

Teminei o curso e o projeto e não sei porque ao executar o lista.xhtml passou a apresentar a seguinte mensagem de erro(lembrando que a aplicacao esta funcionando perfeitamente tanto no index.xhtml quanto no livro-detalhe ):

16:42:46,933 ERROR [io.undertow.request] (default task-44) UT005023: Exception handling request to /casadocodigo/file/: java.lang.RuntimeException: java.io.FileNotFoundException: \casadocodigo (Acesso negado)
    at br.com.casadocodigo.loja.infra.FileSaver.transfer(FileSaver.java:46)
    at br.com.casadocodigo.loja.servlets.FileServlet.service(FileServlet.java:33)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:284)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: \casadocodigo (Acesso negado)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at br.com.casadocodigo.loja.infra.FileSaver.transfer(FileSaver.java:33)
    ... 29 more

public class FileSaver {

    public static final String SERVER_PATH = "/casadocodigo";

    public String write(Part arquivo, String path){

        String relativePath = path +"/"+ arquivo.getSubmittedFileName();
        try {
            arquivo.write(SERVER_PATH +"/"+ relativePath);
            return relativePath;
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public static void transfer(Path source, OutputStream outputStream) {
        try {
            FileInputStream input = new FileInputStream(source.toFile());
            try(ReadableByteChannel inputChannel = Channels.newChannel(input);
                    WritableByteChannel outputChannel = Channels.newChannel(outputStream)){
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10);
                while(inputChannel.read(buffer) != -1){
                    buffer.flip();
                    outputChannel.write(buffer);
                    buffer.clear();
                }
            } catch (IOException e) {                
                throw new RuntimeException(e);
            }
        } catch (File
5 respostas
<!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:ui="http://xmlns.jcp.org/jsf/facelets">


    <h:messages />

    <h:dataTable var="livro" value="#{adminListaLivrosBean.livros}">
        <h:column>
            <f:facet name="header">Título</f:facet>
            #{livro.titulo}
        </h:column>
        <h:column>
            <f:facet name="header">Descrição</f:facet>
            #{livro.descricao}
        </h:column>
        <h:column>
            <f:facet name="header">Páginas</f:facet>
            #{livro.numeroPaginas}
        </h:column>
        <h:column>
            <f:facet name="header">Preço</f:facet>
            #{livro.preco}
        </h:column>
        <h:column>
            <f:facet name="header">Autores</f:facet>
            <ui:repeat value="#{livro.autores}" var="autor">
                #{autor.nome},
            </ui:repeat>
        </h:column>
        <h:column>
            <f:facet name="header">Capa Path</f:facet>
            <img src="#{request.contextPath}/file/#{livro.capaPath}"
                height="30%" alt="#{livro.titulo}" />
        </h:column>
    </h:dataTable>

</html>

Bom dia !

Não consegui o seu log pois não carregou no meu cel, mais caso esteja fazendo o curso utilizando windows faça o teste fazendo as seguintes alterações :

Ao invez de

SERVER_PATH = "/casadocodigo";

 String relativePath = path+"/"+arquivo.getSubmittedFileName();

            arquivo.write(SERVER_PATH +"/"+ relativePath);

mude para duas barras invertidas

SERVER_PATH = "c:\\casadocodigo";  //não esqueça de informar o caminho completo !

 String relativePath = path+"\\"+arquivo.getSubmittedFileName();

            arquivo.write(SERVER_PATH +"\\"+ relativePath);

isso ocorre pois o windows trabalha com barra invertida \ e o mac os do professor trabalha com o mesmo esquema linux /

são duas barras pois apenas uma barra \ acusa erro na string do java por representar um delimitador ja duas barras \ junta o resultado é apenas uma barra \

Espero ter ajudado ou pelo menos agregado alguma informação.

Bons estudos!

Beleza Lucas. Obrigado. Aparentemente ajusta o FileSaver.java. Pode me orientar como deve fazer o devido ajuste no FileServlet.java???? O mesmo erro persiste e acredito que seja por conta disso. Sera que temos mais classes pra ajustar pra funcionar no windows?

package br.com.casadocodigo.loja.servlets;

import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.casadocodigo.loja.infra.FileSaver;

@WebServlet("/file/*")
public class FileServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String path = req.getRequestURI().split("/file")[1];

        Path source = Paths.get(FileSaver.SERVER_PATH + "/" + path);
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor("file:"+ source);

        res.reset();
        res.setContentType(contentType);
        res.setHeader("Content-Length", String.valueOf(Files.size(source)));
        res.setHeader("Content-Disposition", 
                "filename=\""+source.getFileName().toString() + "\"");
        FileSaver.transfer(source, res.getOutputStream());
    }
}

Boa tarde !

creio que com a alteração abaixo resolverá o problema.

FileServlet.java

package br.com.casadocodigo.loja.servlets;

import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.casadocodigo.loja.infra.FileSaver;

@WebServlet("/file/*")
public class FileServlet extends HttpServlet {

    private static final long serialVersionUID = 5366244905779362727L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) 
                throws ServletException, IOException {
        String path = req.getRequestURI().split("/file")[1];

        Path source = Paths.get(FileSaver.SERVER_PATH + "\\" + path);
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor("file:"+source);

        res.reset();
        res.setContentType(contentType);
        res.setHeader("Content-Length", String.valueOf(Files.size(source)));
        res.setHeader("Content-Disposition", 
                "filename=/"+source.getFileName().toString() + "/");
        FileSaver.transfer(source, res.getOutputStream());
    }

}

FileSaver.java

package br.com.casadocodigo.loja.infra;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Path;

import javax.servlet.http.Part;

public class FileSaver {

    public static final String SERVER_PATH = "c:\\casadocodigo";

    public String write(Part arquivo, String path) {
        String relativePath = path + "\\" + arquivo.getSubmittedFileName();
        String fullPath = SERVER_PATH + "\\" + relativePath;
        try {
            arquivo.write(fullPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return relativePath;
    }

    public static void transfer(Path source, OutputStream outputStream) {
        try {
            FileInputStream input = new FileInputStream(source.toFile());
            try( ReadableByteChannel inputChannel = Channels.newChannel(input);
                    WritableByteChannel outputChannel = Channels.newChannel(outputStream)) {
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 10);

                while(inputChannel.read(buffer) != -1) {
                    buffer.flip();
                    outputChannel.write(buffer);
                    buffer.clear();
                }
            } catch (IOException e) {
                throw new RuntimeException(e); 
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e); 
        }
    }
}

não esqueça de criar a pasta casadocodigo e dentro dela a pasta livros

no meu caso ficou em c:\casadocodigo\livros

Bons estudos!

Copiei as duas classes de forma identica e o problema persiste. A execuçao nao esta afetando o meu curso. Mas o que me intriga é que sempre que rodo o lista.xhtml esse erro sempre aparece

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software