@Override
  public void handleResourceRequest(FacesContext context) throws IOException {
    Resource resource = createResource(context);

    if (resource == null) {
      super.handleResourceRequest(context);
      return;
    }

    ExternalContext externalContext = context.getExternalContext();

    if (!resource.userAgentNeedsUpdate(context)) {
      externalContext.setResponseStatus(SC_NOT_MODIFIED);
      return;
    }

    InputStream inputStream = resource.getInputStream();

    if (inputStream == null) {
      externalContext.setResponseStatus(SC_NOT_FOUND);
      return;
    }

    externalContext.setResponseContentType(resource.getContentType());

    for (Entry<String, String> header : resource.getResponseHeaders().entrySet()) {
      externalContext.setResponseHeader(header.getKey(), header.getValue());
    }

    stream(inputStream, externalContext.getResponseOutputStream());
  }
Esempio n. 2
0
 /**
  * Crea un archivo para que pueda ser descargado en el navegador, debe previamente existir el path
  * de archivo
  *
  * @param path
  */
 public void crearArchivo(String path) {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   StreamedContent content;
   InputStream stream = null;
   try {
     if (path.startsWith("/")) {
       stream =
           ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext())
               .getResourceAsStream(path);
     } else {
       stream = new FileInputStream(path);
     }
   } catch (Exception e) {
     crearError("No se puede generar el archivo path: " + path, "crearArchivo()", e);
   }
   if (stream == null) {
     return;
   }
   content = new DefaultStreamedContent(stream);
   if (content == null) {
     return;
   }
   ExternalContext externalContext = facesContext.getExternalContext();
   String contentDispositionValue = "attachment";
   try {
     externalContext.setResponseContentType(content.getContentType());
     externalContext.setResponseHeader(
         "Content-Disposition",
         contentDispositionValue
             + ";filename=\""
             + path.substring(path.lastIndexOf("/") + 1)
             + "\"");
     externalContext.addResponseCookie(
         Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>());
     byte[] buffer = new byte[2048];
     int length;
     InputStream inputStream = content.getStream();
     OutputStream outputStream = externalContext.getResponseOutputStream();
     while ((length = (inputStream.read(buffer))) != -1) {
       outputStream.write(buffer, 0, length);
     }
     externalContext.setResponseStatus(200);
     externalContext.responseFlushBuffer();
     content.getStream().close();
     facesContext.getApplication().getStateManager().saveView(facesContext);
     facesContext.responseComplete();
   } catch (Exception e) {
     crearError("No se puede descargar :  path: " + path, "crearArchivo()", e);
   }
 }