@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
    public DelayedInitPartialResponseWriter(PartialViewContextImpl ctx) {

      super(null);
      this.ctx = ctx;
      ExternalContext extCtx = ctx.ctx.getExternalContext();
      extCtx.setResponseContentType("text/xml");
      extCtx.setResponseCharacterEncoding(extCtx.getRequestCharacterEncoding());
    }
Esempio n. 3
0
 protected void configureResponse(ExternalContext externalContext, String filename) {
   externalContext.setResponseContentType("text/xml");
   externalContext.setResponseHeader("Expires", "0");
   externalContext.setResponseHeader(
       "Cache-Control", "must-revalidate, post-check=0, pre-check=0");
   externalContext.setResponseHeader("Pragma", "public");
   externalContext.setResponseHeader(
       "Content-disposition", "attachment;filename=" + filename + ".xml");
   externalContext.addResponseCookie(
       Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>());
 }
Esempio n. 4
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);
   }
 }
  private void handlePartialResponseError(FacesContext context, Throwable t) {
    if (context.getResponseComplete()) {
      return; // don't write anything if the response is complete
    }
    try {

      ExternalContext extContext = context.getExternalContext();
      extContext.setResponseContentType("text/xml");
      extContext.addResponseHeader("Cache-Control", "no-cache");
      PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();

      writer.startDocument();
      writer.startError(t.getClass().toString());
      String msg;
      if (context.isProjectStage(ProjectStage.Production)) {
        msg = "See your server log for more information";
      } else {
        if (t.getCause() != null) {
          msg = t.getCause().getMessage();
        } else {
          msg = t.getMessage();
        }
      }
      writer.write(((msg != null) ? msg : ""));
      writer.endError();
      writer.endDocument();

      if (LOGGER.isLoggable(Level.SEVERE)) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        LOGGER.log(Level.SEVERE, sw.toString());
      }

      context.responseComplete();
    } catch (IOException ioe) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(Level.SEVERE, ioe.toString(), ioe);
      }
    }
  }
Esempio n. 6
0
  /**
   * @param context the {@link FacesContext} for the current request
   * @return a {@link ResponseWriter} for processing the request
   * @throws IOException if the writer cannot be created
   */
  protected ResponseWriter createResponseWriter(FacesContext context) throws IOException {

    ExternalContext extContext = context.getExternalContext();
    RenderKit renderKit = context.getRenderKit();
    // Avoid a cryptic NullPointerException when the renderkit ID
    // is incorrectly set
    if (renderKit == null) {
      String id = context.getViewRoot().getRenderKitId();
      throw new IllegalStateException("No render kit was available for id \"" + id + "\"");
    }

    if (responseBufferSizeSet) {
      // set the buffer for content
      extContext.setResponseBufferSize(responseBufferSize);
    }

    // get our content type
    String contentType = (String) extContext.getRequestMap().get("facelets.ContentType");

    // get the encoding
    String encoding = (String) extContext.getRequestMap().get("facelets.Encoding");

    // Create a dummy ResponseWriter with a bogus writer,
    // so we can figure out what content type the ReponseWriter
    // is really going to ask for
    ResponseWriter writer =
        renderKit.createResponseWriter(NullWriter.Instance, contentType, encoding);

    contentType = getResponseContentType(context, writer.getContentType());
    encoding = getResponseEncoding(context, writer.getCharacterEncoding());

    // apply them to the response
    extContext.setResponseContentType(contentType);
    extContext.setResponseCharacterEncoding(encoding);

    // Now, clone with the real writer
    writer = writer.cloneWithWriter(extContext.getResponseOutputWriter());

    return writer;
  }
  public void download(String fileName) {
    for (ServerInfo info : servers) {
      try (Socket server = info.getSocket();
          OutputStream os = server.getOutputStream();
          PrintWriter pw = new PrintWriter(os);
          InputStream is = server.getInputStream()) {

        /*Protocol*/
        os.write(Protocol.DOWNLOAD);
        pw.println(fileName);
        pw.flush();

        /*Check if file exists, 1 if present, 0 if otherwise*/
        int reply = is.read();
        if (reply == 1) {

          /*Response header*/
          FacesContext fc = FacesContext.getCurrentInstance();
          ExternalContext ec = fc.getExternalContext();
          ec.responseReset();
          ec.setResponseContentType(ec.getMimeType(fileName));
          ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

          /*Write bytes*/
          transferBytes(is, ec.getResponseOutputStream());
          fc.responseComplete();
          System.out.println(
              "File " + fileName + " was successfully downloaded with size " + file.getSize());
          break;
        }
      } catch (ConnectException e) {
        // Socket is closed
        System.out.println(e + " download at " + info);
      } catch (IOException ex) {
        Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Esempio n. 8
0
File: App.java Progetto: ndrew/bndr
  public void jsonStatus() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    Session session =
        (Session) context.getApplication().evaluateExpressionGet(context, "#{auth}", Session.class);

    String data = "{\"status\": \"not-logged-in\"}";

    if (session.isUserLoggedIn()) {
      if (null == this.data) {
        data = "{\"status\": \"waiting for app\"}";
        this.data = "foo";
      } else {
        data = "{\"status\": \"done\"}";
      }
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/json");
    externalContext.setResponseCharacterEncoding("UTF-8");
    externalContext.getResponseOutputWriter().write(data);
    facesContext.responseComplete();
  }
Esempio n. 9
0
  /** @see javax.faces.context.PartialViewContext#processPartial(javax.faces.event.PhaseId)) */
  @Override
  public void processPartial(PhaseId phaseId) {
    Collection<String> executeIds = getExecuteIds();
    Collection<String> renderIds = getRenderIds();
    UIViewRoot viewRoot = ctx.getViewRoot();

    if (phaseId == PhaseId.APPLY_REQUEST_VALUES
        || phaseId == PhaseId.PROCESS_VALIDATIONS
        || phaseId == PhaseId.UPDATE_MODEL_VALUES) {

      // Skip this processing if "none" is specified in the render list,
      // or there were no execute phase client ids.

      if (executeIds == null || executeIds.isEmpty()) {
        // RELEASE_PENDING LOG ERROR OR WARNING
        return;
      }

      try {
        processComponents(viewRoot, phaseId, executeIds, ctx);
      } catch (Exception e) {
        // RELEASE_PENDING LOG EXCEPTION
      }

      // If we have just finished APPLY_REQUEST_VALUES phase, install the
      // partial response writer.  We want to make sure that any content
      // or errors generated in the other phases are written using the
      // partial response writer.
      //
      if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
        PartialResponseWriter writer = getPartialResponseWriter();
        ctx.setResponseWriter(writer);
      }

    } else if (phaseId == PhaseId.RENDER_RESPONSE) {

      try {
        //
        // We re-enable response writing.
        //
        OnOffResponseWrapper onOffResponse = new OnOffResponseWrapper(ctx);
        onOffResponse.setEnabled(true);
        PartialResponseWriter writer = getPartialResponseWriter();
        ResponseWriter orig = ctx.getResponseWriter();
        ctx.getAttributes().put(ORIGINAL_WRITER, orig);
        ctx.setResponseWriter(writer);

        ExternalContext exContext = ctx.getExternalContext();
        exContext.setResponseContentType("text/xml");
        exContext.addResponseHeader("Cache-Control", "no-cache");
        writer.startDocument();
        if (isRenderAll()) {
          renderAll(ctx, viewRoot);
          renderState(ctx);
          writer.endDocument();
          return;
        }

        // Skip this processing if "none" is specified in the render list,
        // or there were no render phase client ids.
        if (renderIds == null || renderIds.isEmpty()) {
        } else {
          processComponents(viewRoot, phaseId, renderIds, ctx);
        }

        renderState(ctx);

        writer.endDocument();
      } catch (IOException ex) {
        this.cleanupAfterView();
      } catch (RuntimeException ex) {
        this.cleanupAfterView();
        // Throw the exception
        throw ex;
      }
    }
  }
Esempio n. 10
0
  /** @see javax.faces.context.PartialViewContext#processPartial(javax.faces.event.PhaseId)) */
  @Override
  public void processPartial(PhaseId phaseId) {
    updateFacesContext();
    PartialViewContext pvc = ctx.getPartialViewContext();
    Collection<String> executeIds = pvc.getExecuteIds();
    Collection<String> renderIds = pvc.getRenderIds();
    UIViewRoot viewRoot = ctx.getViewRoot();

    if (phaseId == PhaseId.APPLY_REQUEST_VALUES
        || phaseId == PhaseId.PROCESS_VALIDATIONS
        || phaseId == PhaseId.UPDATE_MODEL_VALUES) {

      // Skip this processing if "none" is specified in the render list,
      // or there were no execute phase client ids.

      if (executeIds == null || executeIds.isEmpty()) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.log(
              Level.FINE,
              "No execute and render identifiers specified.  Skipping component processing.");
        }
        return;
      }

      try {
        processComponents(viewRoot, phaseId, executeIds, ctx);
      } catch (Exception e) {
        if (LOGGER.isLoggable(Level.INFO)) {
          LOGGER.log(Level.INFO, e.toString(), e);
        }
      }

      // If we have just finished APPLY_REQUEST_VALUES phase, install the
      // partial response writer.  We want to make sure that any content
      // or errors generated in the other phases are written using the
      // partial response writer.
      //
      if (phaseId == PhaseId.APPLY_REQUEST_VALUES) {
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        ctx.setResponseWriter(writer);
      }

    } else if (phaseId == PhaseId.RENDER_RESPONSE) {

      try {
        //
        // We re-enable response writing.
        //
        PartialResponseWriter writer = pvc.getPartialResponseWriter();
        ResponseWriter orig = ctx.getResponseWriter();
        ctx.getAttributes().put(ORIGINAL_WRITER, orig);
        ctx.setResponseWriter(writer);

        ExternalContext exContext = ctx.getExternalContext();
        exContext.setResponseContentType("text/xml");
        exContext.addResponseHeader("Cache-Control", "no-cache");
        writer.startDocument();
        if (isRenderAll()) {
          renderAll(ctx, viewRoot);
          renderState(ctx);
          writer.endDocument();
          return;
        }

        // Skip this processing if "none" is specified in the render list,
        // or there were no render phase client ids.
        if (renderIds == null || renderIds.isEmpty()) {
        } else {
          processComponents(viewRoot, phaseId, renderIds, ctx);
        }

        renderState(ctx);

        writer.endDocument();
      } catch (IOException ex) {
        this.cleanupAfterView();
      } catch (RuntimeException ex) {
        this.cleanupAfterView();
        // Throw the exception
        throw ex;
      }
    }
  }