protected void verify(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    String viewId = facesContext.getViewRoot().getViewId();
    SecurityBean securityBean = SecurityBean.getInstance();

    /*
     * Primero se valida que la sesión no haya caducado
     * */
    if (SecurityBean.isSessionExpired(facesContext)) {
      try {
        doRedirect(facesContext, "/resources/errorpages/errorSessionExpired.jsp");
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }

    } else if (!securityBean.verifyPageAccess(viewId)) {
      /*
       * Luego se valida que no se esté accediendo a un recurso sin autenticación
       * */
      HttpServletResponse response =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      try {
        response.sendError(403); // 403: Forbidden error
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #2
0
 /**
  * Downloads a blob and sends it to the requesting user, in the JSF current context.
  *
  * @param doc the document, if available
  * @param xpath the blob's xpath or blobholder index, if available
  * @param blob the blob, if already fetched
  * @param filename the filename to use
  * @param reason the download reason
  * @param extendedInfos an optional map of extended informations to log
  * @since 7.3
  */
 public static void download(
     DocumentModel doc,
     String xpath,
     Blob blob,
     String filename,
     String reason,
     Map<String, Serializable> extendedInfos) {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   if (facesContext.getResponseComplete()) {
     // nothing can be written, an error was probably already sent. don't bother
     log.debug("Cannot send " + filename + ", response already complete");
     return;
   }
   if (facesContext.getPartialViewContext().isAjaxRequest()) {
     // do not perform download in an ajax request
     return;
   }
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
   HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
   try {
     DownloadService downloadService = Framework.getService(DownloadService.class);
     downloadService.downloadBlob(
         request, response, doc, xpath, blob, filename, reason, extendedInfos);
   } catch (IOException e) {
     log.error("Error while downloading the file: " + filename, e);
   } finally {
     facesContext.responseComplete();
   }
 }
Example #3
0
  /** Generates a PDF with the list of registered members in the event. */
  public void print() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "inline=filename=file.pdf");

    try {
      Document document = new Document();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, baos);
      document.open();

      EventAttendeeReport eventAttendeeReport = new EventAttendeeReport(document);
      eventAttendeeReport.printReport(this.attendees);

      document.close();

      response.getOutputStream().write(baos.toByteArray());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      context.responseComplete();
    } catch (IOException | DocumentException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
  }
Example #4
0
  /**
   * @see javax.faces.view.ViewDeclarationLanguage#buildView(javax.faces.context.FacesContext,
   *     javax.faces.component.UIViewRoot)
   * @param context
   * @param view
   * @throws IOException
   */
  public void buildView(FacesContext context, UIViewRoot view) throws IOException {

    if (Util.isViewPopulated(context, view)) {
      return;
    }
    try {
      if (executePageToBuildView(context, view)) {
        context.getExternalContext().responseFlushBuffer();
        if (associate != null) {
          associate.responseRendered();
        }
        context.responseComplete();
        return;
      }
    } catch (IOException e) {
      throw new FacesException(e);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Completed building view for : \n" + view.getViewId());
    }
    context
        .getApplication()
        .publishEvent(context, PostAddToViewEvent.class, UIViewRoot.class, view);
    Util.setViewPopulated(context, view);
  }
  public void executeReport() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();

    HttpServletResponse response =
        (HttpServletResponse) facesContext.getExternalContext().getResponse();

    InputStream reportStream =
        facesContext.getExternalContext().getResourceAsStream("caminho_arquivo.jasper");

    response.setContentType("application/pdf");

    response.setHeader("Content-disposition", "inline;filename=relatorio.pdf");

    try {
      ServletOutputStream servletOutputStream = response.getOutputStream();

      JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(arrayList);

      JasperRunManager.runReportToPdfStream(
          reportStream, servletOutputStream, parameters, datasource);

      servletOutputStream.flush();
      servletOutputStream.close();
    } catch (JRException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      facesContext.responseComplete();
    }
  }
  public static void imprimeRelatorio(String nomeRelatorio, HashMap parametros, List lista) {
    try {
      JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(lista);
      FacesContext facesContext = FacesContext.getCurrentInstance();
      ServletContext servletContext =
          (ServletContext) facesContext.getExternalContext().getContext();
      String path = servletContext.getRealPath("/WEB-INF/relatorios/");
      // parametro jasper report
      parametros.put("SUBREPORT DIR", path + File.separator);
      JasperPrint jasperPrint =
          JasperFillManager.fillReport(
              servletContext.getRealPath("/WEB-INF/relatorios/")
                  + File.separator
                  + nomeRelatorio
                  + ".jasper",
              parametros,
              dataSource);
      byte[] b = JasperExportManager.exportReportToPdf(jasperPrint);

      HttpServletResponse res =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      res.setContentType("application/pdf");
      int codigo = (int) (Math.random() * 1000);
      res.setHeader("Content-disposition", "inline);filename-relatorio_" + codigo + ".pdf");
      res.getOutputStream().write(b);
      facesContext.responseComplete();

    } catch (Exception e) {
      UtilMensagens.mensagemErro("Erro ao imprimir: " + UtilErros.getMensagemErro(e));
      e.printStackTrace();
    }
  }
Example #7
0
  public String logout() {
    boolean isShib2Authentication =
        OxTrustConstants.APPLICATION_AUTHORIZATION_NAME_SHIBBOLETH2.equals(
            Contexts.getSessionContext().get(OxTrustConstants.APPLICATION_AUTHORIZATION_TYPE));

    if (isShib2Authentication) {
      // After this redirect we should invalidate this session
      try {
        HttpServletResponse userResponse =
            (HttpServletResponse) facesContext.getExternalContext().getResponse();
        HttpServletRequest userRequest =
            (HttpServletRequest) facesContext.getExternalContext().getRequest();

        String redirectUrl =
            String.format("%s%s", applicationConfiguration.getIdpUrl(), "/idp/logout.jsp");
        String url =
            String.format(
                "%s://%s/Shibboleth.sso/Logout?return=%s",
                userRequest.getScheme(), userRequest.getServerName(), redirectUrl);

        userResponse.sendRedirect(url);
        facesContext.responseComplete();
      } catch (IOException ex) {
        log.error("Failed to redirect to SSO logout page", ex);
      }
    }

    return isShib2Authentication
        ? OxTrustConstants.RESULT_LOGOUT_SSO
        : OxTrustConstants.RESULT_LOGOUT;
  }
Example #8
0
  /**
   * Send {@link HttpServletResponse#SC_NOT_FOUND} (404) to the client.
   *
   * @param context the {@link FacesContext} for the current request
   */
  protected void send404Error(FacesContext context) {

    try {
      context.responseComplete();
      context.getExternalContext().responseSendError(HttpServletResponse.SC_NOT_FOUND, "");
    } catch (IOException ioe) {
      throw new FacesException(ioe);
    }
  }
Example #9
0
  /**
   * Handles the case where a Facelet cannot be found.
   *
   * @param context the {@link FacesContext} for the current request
   * @param viewId the view ID that was to be mapped to a Facelet
   * @param message optional message to include in the 404
   * @throws IOException if an error occurs sending the 404 to the client
   */
  protected void handleFaceletNotFound(FacesContext context, String viewId, String message)
      throws IOException {

    context
        .getExternalContext()
        .responseSendError(
            HttpServletResponse.SC_NOT_FOUND,
            ((message != null) ? (viewId + ": " + message) : viewId));
    context.responseComplete();
  }
Example #10
0
 public static void redirect(FacesContext context, String path) {
   RedirectScope.setRedirectingPath(context, path);
   ExternalContext externalContext = context.getExternalContext();
   try {
     externalContext.redirect(externalContext.encodeActionURL(path));
   } catch (IOException e) {
     throw new FacesException(e.getMessage(), e);
   }
   context.responseComplete();
   context.renderResponse();
 }
 public void handleReturnValue(
     Object returnValue,
     MethodParameter returnType,
     ModelAndViewContainer mavContainer,
     NativeWebRequest webRequest)
     throws Exception {
   this.handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
   FacesContext context = FacesContext.getCurrentInstance();
   if (context != null) {
     context.responseComplete();
   }
 }
 /** @throws IOException */
 public void exportXLS() throws IOException {
   DataTable tabla =
       (DataTable)
           FacesContext.getCurrentInstance()
               .getViewRoot()
               .findComponent("formExportar:datosEmpresasExportar");
   FacesContext context = FacesContext.getCurrentInstance();
   Exporter exporter = new ExportarXLS();
   exporter.export(context, tabla, "CentroCostos", false, false, "UTF-8", null, null);
   context.responseComplete();
   index = -1;
 }
Example #13
0
  public String exportAllData() {

    Identity.setSecurityEnabled(false);

    Collection<ContentItem> items = getContentItemService().getContentItems();

    File f = new File(pathToExportFile);
    OutputStream out = null;
    try {
      out = FileUtils.openOutputStream(f);
      exporter.exportItems(items, "application/x-kiwi", out);
    } catch (IOException ex) {
      log.error("Error by creating zip file #0", ex.getMessage());
    } finally {
      try {
        out.close();
      } catch (IOException ex) {
        log.error("Error by close outputstream #0", ex.getMessage());
      }
    }

    log.info("Create export file #0", f.getAbsolutePath());

    try {
      InputStream newIs = new FileInputStream(f);
      byte[] baBinary = new byte[newIs.available()];
      newIs.read(baBinary);

      HttpServletResponse response = (HttpServletResponse) extCtx.getResponse();

      String contentType = "application/zip";
      String fileName = "export.kiwi";

      response.setContentType(contentType);
      response.addHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");

      ServletOutputStream os = response.getOutputStream();
      os.write(baBinary);
      os.flush();
      os.close();
      facesContext.responseComplete();
    } catch (Exception ex) {
      log.error("Error by downloading file #0", ex.getMessage());
    } finally {
      try {
        out.close();
      } catch (IOException ex) {
        log.error("Error by close outputstream #0", ex.getMessage());
      }
    }

    return null;
  }
  // Redireciona Pagina
  private void redirect(String path) {
    try {
      FacesContext context = FacesContext.getCurrentInstance();
      ExternalContext externalContext = context.getExternalContext();
      String requestContextPath = externalContext.getRequestContextPath();

      externalContext.redirect(requestContextPath + path);
      context.responseComplete();
    } catch (IOException e) {

      throw new RuntimeException(e);
    }
  }
Example #15
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void gerarRelatorio(
      String nomeJasper, String attachmentName, List<?> dataSource, Map parametros, String tipo)
      throws JRException, IOException {

    FacesContext fContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fContext.getExternalContext();

    // Busca o local onde esta o jasper
    InputStream fis = externalContext.getResourceAsStream(PATH + nomeJasper);
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fis);

    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    // Abre a figura e seta o parâmetro do relatório
    InputStream imgInputStream =
        this.getClass().getResourceAsStream("resources/images/logo/" + "fmb.gif");
    parametros.put("IMG_BRASAO", imgInputStream);

    StringBuffer filename = new StringBuffer(attachmentName);

    JRDataSource ds = new JRBeanCollectionDataSource(dataSource);
    byte[] bytes = null;

    if (tipo.equals("P")) {
      bytes = this.gerarRelatorioJasperPDF(jasperReport, parametros, ds);
      response.setContentType("application/pdf");
      filename.append(".pdf").toString();
      response.addHeader("content-disposition", "attachment;filename=" + filename);
    } else if (tipo.equals("X")) {
      bytes = this.gerarRelatorioJasperXLS(jasperReport, parametros, ds);
      response.setContentType("application/vnd.ms-excel");
      filename.append(".xls").toString();
      response.addHeader("content-disposition", "attachment;filename=" + filename);
    } else if (tipo.equals("D")) {
      bytes = this.gerarRelatorioJasperDoc(jasperReport, parametros, ds);
      response.setContentType("application/rtf");
      filename.append(".rtf").toString();
      response.addHeader("content-disposition", "attachment;filename=" + filename);
    }

    if (bytes != null && bytes.length > 0) {
      response.setContentLength(bytes.length);

      ServletOutputStream ouputStream = response.getOutputStream();
      ouputStream.write(bytes, 0, bytes.length);
      ouputStream.flush();
      ouputStream.close();
      fContext.responseComplete();
    }
  }
Example #16
0
  /**
   * Determine the next view based on the current view (<code>from-view-id</code> stored in <code>
   * FacesContext</code>), <code>fromAction</code> and <code>outcome</code>.
   *
   * @param context The <code>FacesContext</code>
   * @param fromAction the action reference string
   * @param outcome the outcome string
   */
  public void handleNavigation(FacesContext context, String fromAction, String outcome) {
    if (context == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }
    if (outcome == null) {
      return; // Explicitly remain on the current view
    }
    CaseStruct caseStruct = getViewId(context, fromAction, outcome);
    ExternalContext extContext = context.getExternalContext();
    if (caseStruct != null) {
      ViewHandler viewHandler = Util.getViewHandler(context);
      assert (null != viewHandler);

      if (caseStruct.navCase.isRedirect()) {
        // perform a 302 redirect.
        String newPath = viewHandler.getActionURL(context, caseStruct.viewId);
        try {
          if (logger.isLoggable(Level.FINE)) {
            logger.fine(
                "Redirecting to path "
                    + newPath
                    + " for outcome "
                    + outcome
                    + "and viewId "
                    + caseStruct.viewId);
          }
          // encode the redirect to ensure session state
          // is maintained
          extContext.redirect(extContext.encodeActionURL(newPath));
        } catch (java.io.IOException ioe) {
          if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "jsf.redirect_failed_error", newPath);
          }
          throw new FacesException(ioe.getMessage(), ioe);
        }
        context.responseComplete();
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Response complete for " + caseStruct.viewId);
        }
      } else {
        UIViewRoot newRoot = viewHandler.createView(context, caseStruct.viewId);
        context.setViewRoot(newRoot);
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Set new view in FacesContext for " + caseStruct.viewId);
        }
      }
    }
  }
Example #17
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);
   }
 }
Example #18
0
 public String logout() throws IOException {
   String tmpUsername = this.username;
   FacesContext context = FacesContext.getCurrentInstance();
   String contextPath = context.getExternalContext().getRequestContextPath();
   context.getExternalContext().redirect(contextPath + "/login.jspx");
   username = null;
   userrole = 4;
   context.responseComplete();
   /*DatabasePolicy.removeEntityPermissionCacheEntry(tmpUsername);*/
   HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
   session.setAttribute("FILTER_SUBJECT", null);
   // Session will be invalidate in the loggedOut.jsp page
   return "logout";
 }
Example #19
0
 /**
  * Perform the navigation to the @LoginView. If not @LoginView is defined, return a 401 response.
  * The original view id requested by the user is stored in the session map, for use after a
  * successful login.
  *
  * @param context
  * @param viewRoot
  */
 private void redirectToLoginPage(FacesContext context, UIViewRoot viewRoot) {
   Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
   preLoginEvent.fire(new PreLoginEvent(context, sessionMap));
   LoginView loginView = viewConfigStore.getAnnotationData(viewRoot.getViewId(), LoginView.class);
   if (loginView == null || loginView.value() == null || loginView.value().isEmpty()) {
     log.debug("Returning 401 response (login required)");
     context.getExternalContext().setResponseStatus(401);
     context.responseComplete();
     return;
   }
   String loginViewId = loginView.value();
   log.debugf("Redirecting to configured LoginView %s", loginViewId);
   NavigationHandler navHandler = context.getApplication().getNavigationHandler();
   navHandler.handleNavigation(context, "", loginViewId);
   context.renderResponse();
 }
  @SuppressWarnings({"rawtypes"})
  public static synchronized void gerarRelatorio(
      List<? extends Entidade> lista, String formato, String caminhoImagem)
      throws JRException, IOException {
    if (lista != null && !lista.isEmpty()) {
      DynamicReport relatorio = criaRelatorioDinamico(lista, caminhoImagem);
      FacesContext context = FacesContext.getCurrentInstance();
      HttpServletResponse response =
          (HttpServletResponse) context.getExternalContext().getResponse();

      JasperPrint jasperPrint =
          DynamicJasperHelper.generateJasperPrint(relatorio, new ClassicLayoutManager(), lista);

      JRExporter jrExporter = null;
      String contentType = null;

      if ("PDF".equalsIgnoreCase(formato)) {
        jrExporter = new JRPdfExporter();
        contentType = "application/pdf";
      }

      if ("XLS".equalsIgnoreCase(formato)) {
        jrExporter = new JRXlsExporter();
        contentType = "application/vnd.ms-excel";
        jrExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
        jrExporter.setParameter(
            JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
        jrExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
      }

      response.setContentType(contentType);
      response.setHeader(
          "Content-Disposition",
          "attachment; filename=" + relatorio.getReportName() + "." + formato.toLowerCase());

      ServletOutputStream outputStream = response.getOutputStream();

      jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
      jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
      jrExporter.exportReport();
      outputStream.flush();
      outputStream.close();
      context.renderResponse();
      context.responseComplete();
    }
  }
  /**
   * Determines if the user is authenticated. If not, direct the user to the login view, otherwise
   * all the user to continue to the requested view.
   *
   * <p>Implementation Note: We do this in the <code>afterPhase</code> to make use of the <code>
   * NavigationHandler</code>.
   */
  public void afterPhase(PhaseEvent event) {
    FacesContext context = event.getFacesContext();

    if (userExists(context)) {
      // allow processing of the requested view
      return;
    } else {
      // send the user to the login view
      if (requestingSecureView(context)) {
        context.responseComplete();
        context
            .getApplication()
            .getNavigationHandler()
            .handleNavigation(context, null, USER_LOGIN_OUTCOME);
      }
    }
  }
Example #22
0
 /**
  * Perform the navigation to the @AccessDeniedView. If not @AccessDeniedView is defined, return a
  * 401 response
  *
  * @param context
  * @param viewRoot
  */
 private void redirectToAccessDeniedView(FacesContext context, UIViewRoot viewRoot) {
   AccessDeniedView accessDeniedView =
       viewConfigStore.getAnnotationData(viewRoot.getViewId(), AccessDeniedView.class);
   if (accessDeniedView == null
       || accessDeniedView.value() == null
       || accessDeniedView.value().isEmpty()) {
     log.debug("Returning 401 response (access denied)");
     context.getExternalContext().setResponseStatus(401);
     context.responseComplete();
     return;
   }
   String accessDeniedViewId = accessDeniedView.value();
   log.debugf("Redirecting to configured AccessDenied %s", accessDeniedViewId);
   NavigationHandler navHandler = context.getApplication().getNavigationHandler();
   navHandler.handleNavigation(context, "", accessDeniedViewId);
   context.renderResponse();
 }
Example #23
0
 public void exportExcelData(StringBuffer sb) {
   byte[] csvData = sb.toString().getBytes();
   FacesContext context = FacesContext.getCurrentInstance();
   HttpServletResponse response =
       (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
   response.setHeader("Content-disposition", "attachment; filename=convertido.csv");
   response.setContentLength(sb.length());
   response.setContentType("text/csv");
   try {
     response.getOutputStream().write(csvData);
     response.getOutputStream().flush();
     response.getOutputStream().close();
     context.responseComplete();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #24
0
  public String login() throws IOException {
    try {
      LoginContext loginContext =
          new LoginContext("InetJaas", new InetCallbackHandler(username, password));
      loginContext.login();
      Subject subject = loginContext.getSubject();
      FacesContext context = FacesContext.getCurrentInstance();
      HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
      session.setAttribute("FILTER_SUBJECT", subject);
      this.setUserrole();

      // WebAuthentication webAuthentication = new WebAuthentication();
      // if (!webAuthentication.login(username, password)) {
      // FacesContext context = FacesContext.getCurrentInstance();
      // String message = MessageBundleHelper.getMessageResourceString(
      // "messages", "userInvalidCredentials", null, context
      // .getExternalContext().getRequestLocale());
      // context.addMessage(null, new FacesMessage(
      // FacesMessage.SEVERITY_ERROR, message, message));
      // return "failure";
      // }
      HttpServletResponse response =
          (HttpServletResponse) context.getExternalContext().getResponse();
      response.sendRedirect(context.getExternalContext().encodeResourceURL("index.jspx"));
      context.responseComplete();
      return "success";

    } catch (LoginException e) {
      FacesContext context = FacesContext.getCurrentInstance();
      String message =
          MessageBundleHelper.getMessageResourceString(
              "messages",
              "userInvalidCredentials",
              null,
              context.getExternalContext().getRequestLocale());
      context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
      return "failure";
    } catch (IOException e) {
      logger.log(Level.SEVERE, "Could not redirect!", e);
      throw new RuntimeException(e);
    } finally {
      wipePassword();
    }
  }
Example #25
0
  /**
   * Crea un archivo comprimido de varios archivo
   *
   * @param archivos arreglo de File con el numero de archivos
   * @param nombrearchivo nombre del archivo comprimido
   */
  public void crearArchivoZIP(File[] archivos, String nombrearchivo) throws Exception {
    // http://www.devtroce.com/2010/06/25/comprimir-y-descomprir-archivos-zip-con-java/
    int BUFFER_SIZE = 1024;
    // objetos en memoria
    FileInputStream fis = null;
    ZipOutputStream zipos = null;
    if (nombrearchivo.indexOf(".zip") < 0) {
      nombrearchivo.concat(".zip");
    }
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
    resp.addHeader("Content-Disposition", "attachment; filename=\"" + nombrearchivo + "\"");

    // buffer
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
      // fichero comprimido
      zipos = new ZipOutputStream(resp.getOutputStream());
      for (File pFile : archivos) {
        // fichero a comprimir
        fis = new FileInputStream(pFile);
        ZipEntry zipEntry = new ZipEntry(pFile.getName());
        zipos.putNextEntry(zipEntry);
        int len = 0;
        // zippear
        while ((len = fis.read(buffer, 0, BUFFER_SIZE)) != -1) {
          zipos.write(buffer, 0, len);
        }
      }
      // volcar la memoria al disco
      zipos.flush();
    } catch (Exception e) {
      throw e;
    } finally {
      // cerramos los files
      zipos.close();
      fis.close();
      fc.getApplication().getStateManager().saveView(fc);
      fc.responseComplete();
    }
  }
  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);
      }
    }
  }
  @Override
  public void afterPhase(PhaseEvent event) {
    ExceptionHandler exceptionHandler = event.getFacesContext().getExceptionHandler();
    if (Iterables.isEmpty(exceptionHandler.getUnhandledExceptionQueuedEvents())) {
      return;
    }

    try {
      new OptimisticLockExceptionHandler(exceptionHandler).handle();

      FacesContext faces = FacesContext.getCurrentInstance();
      String nextUrl = ConversationManager.getInstance().getCurrentConversation().nextUrl();

      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      String url = externalContext.getRequestContextPath() + nextUrl;
      faces.getExternalContext().redirect(url);
      faces.responseComplete();
    } catch (IOException e) {
      log.error("Failed to redirect to context page in render response phase", e);
    }
  }
Example #28
0
  /**
   * Crea un archivo comprimido de varios archivo
   *
   * @param archivos arreglo de File con el numero de archivos
   * @param nombrearchivo nombre del archivo comprimido
   */
  public void downloadArchivo(String nombre_archivo) throws IOException {
    System.out.println("llega el archivo " + nombre_archivo);

    String archivo = "http://localhost:8082/sampu/" + nombre_archivo;
    File ficheroXLS = new File(archivo);
    System.out.println("path " + ficheroXLS.getPath());
    // System.out.println("path cano "+ficheroXLS.getCanonicalPath());
    System.out.println("path absolute " + ficheroXLS.getAbsolutePath());

    FacesContext ctx = FacesContext.getCurrentInstance();
    FileInputStream fis = new FileInputStream(ficheroXLS);
    byte[] bytes = new byte[2048];
    int read = 0;

    if (!ctx.getResponseComplete()) {
      String fileName = ficheroXLS.getName();
      // String contentType = "application/vnd.ms-excel";
      URL u = new URL("file:" + ficheroXLS);
      URLConnection uc = u.openConnection();
      String type = uc.getContentType();

      // System.out.println("Content type of file '"+ficheroXLS+"' is "+type);
      String contentType = type;
      HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

      response.setContentType(contentType);

      response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

      ServletOutputStream out = response.getOutputStream();

      while ((read = fis.read(bytes)) != -1) {
        out.write(bytes, 0, read);
      }

      out.flush();
      out.close();
      ctx.responseComplete();
    }
  }
 public void wordExport() {
   String encodingType = "UTF-8";
   FacesContext facesContext = FacesContext.getCurrentInstance();
   try {
     String outputFileName = getModelName().toLowerCase(Locale.ENGLISH) + "Listesi";
     Exporter exporter = new WordExporter();
     int[] excludedColumns = new int[0];
     exporter.export(
         facesContext,
         getTable(),
         outputFileName,
         false,
         false,
         excludedColumns,
         encodingType,
         null,
         null);
     facesContext.responseComplete();
   } catch (IOException e) {
     throw new FacesException(e);
   }
 }
 @Override
 public void beforePhase(PhaseEvent event) {
   FacesContext facesContext = event.getFacesContext();
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpSession httpSession = (HttpSession) externalContext.getSession(false);
   boolean newSession = (httpSession == null) || (httpSession.isNew());
   boolean postBack = !externalContext.getRequestParameterMap().isEmpty();
   boolean timedOut = postBack && newSession;
   if (timedOut) {
     Application application = facesContext.getApplication();
     ViewHandler viewHandler = application.getViewHandler();
     UIViewRoot view = viewHandler.createView(facesContext, "/main.xhtml");
     facesContext.setViewRoot(view);
     facesContext.renderResponse();
     try {
       viewHandler.renderView(facesContext, view);
       facesContext.responseComplete();
     } catch (Exception e) {
       throw new FacesException("Session timed out", e);
     }
   }
 }