Ejemplo n.º 1
0
  @Override
  public void processUpdates(FacesContext context) {
    if (context == null) {
      throw new NullPointerException();
    }

    // Skip processing if our rendered flag is false
    if (!isRendered()) {
      return;
    }

    processFacetsAndChildrenWithVariable(context, PhaseId.UPDATE_MODEL_VALUES);

    if (Boolean.TRUE.equals(getSubmitValue())) {
      try {
        updateModel(context);
      } catch (RuntimeException e) {
        context.renderResponse();
        throw e;
      }
    }

    if (!isValid()) {
      context.renderResponse();
    }
  }
Ejemplo n.º 2
0
  private void restoreView(FacesContext context) throws FacesException {
    Application app = context.getApplication();

    if (app instanceof ApplicationImpl) ((ApplicationImpl) app).initRequest();

    ViewHandler view = app.getViewHandler();

    view.initView(context);

    UIViewRoot viewRoot = context.getViewRoot();

    if (viewRoot != null) {
      ExternalContext extContext = context.getExternalContext();

      viewRoot.setLocale(extContext.getRequestLocale());

      doSetBindings(context.getELContext(), viewRoot);

      return;
    }

    String viewId = calculateViewId(context);

    String renderKitId = view.calculateRenderKitId(context);

    RenderKitFactory renderKitFactory =
        (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);

    RenderKit renderKit = renderKitFactory.getRenderKit(context, renderKitId);

    ResponseStateManager stateManager = renderKit.getResponseStateManager();

    if (stateManager.isPostback(context)) {
      viewRoot = view.restoreView(context, viewId);

      if (viewRoot != null) {
        doSetBindings(context.getELContext(), viewRoot);
      } else {
        // XXX: backward compat issues with ViewHandler and StateManager

        // throw new ViewExpiredException(L.l("{0} is an expired view", viewId));

        context.renderResponse();

        viewRoot = view.createView(context, viewId);

        context.setViewRoot(viewRoot);
      }

      context.setViewRoot(viewRoot);
    } else {
      context.renderResponse();

      viewRoot = view.createView(context, viewId);

      context.setViewRoot(viewRoot);
    }
  }
Ejemplo n.º 3
0
  /** Executes validation logic. */
  private void executeValidate(FacesContext context) {
    try {
      validate(context);
    } catch (RuntimeException e) {
      context.renderResponse();
      throw e;
    }

    if (!isValid()) {
      context.renderResponse();
    }
  }
Ejemplo n.º 4
0
  protected void processDecodes(FacesContext faces, Object argument) {
    if (!this.isRendered()) return;
    this.decode(faces);

    SubmittedValue submittedValue = UIOrderingList.this.submittedValueHolder;
    if (submittedValue != null) {
      Object modelValue = getValue();
      Iterator iterator = submittedValue.dataMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Entry entry = (Entry) iterator.next();
        Object value = entry.getValue();

        if (!isSuitableValue(modelValue, value)) {
          String messageText =
              Messages.getMessage(Messages.INVALID_VALUE, MessageUtil.getLabel(faces, this), value);

          FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageText, null);
          faces.addMessage(this.getClientId(faces), message);

          setValid(false);
          break;
        }
      }
    }

    this.iterate(faces, decodeVisitor, argument);

    if (isImmediate()) {
      executeValidate(faces);
    }

    if (!isValid()) {
      faces.renderResponse();
    }
  }
  @Override
  public void handle() throws FacesException {
    for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
        i.hasNext(); ) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      Throwable t = context.getException();
      if (t instanceof ViewExpiredException) {
        ViewExpiredException vee = (ViewExpiredException) t;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap();
        NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
        try {
          // Push some useful stuff to the request scope for use in the page
          requestMap.put("currentViewId", vee.getViewId());
          navigationHandler.handleNavigation(facesContext, null, "/viewExpired");
          facesContext.renderResponse();
        } finally {
          i.remove();
        }
      }
    }

    // At this point, the queue will not contain any ViewExpiredEvents. Therefore, let the parent
    // handle them.
    getWrapped().handle();
  }
  @Override
  public void handle() throws FacesException {
    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();

    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      Throwable t = context.getException();

      final FacesContext fc = FacesContext.getCurrentInstance();
      final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();

      try {
        System.out.printf(">>> Exception caught: %s", t.getMessage());
        t.printStackTrace();

        requestMap.put("exceptionMessage", t.getMessage());

        ExternalContext extContext = fc.getExternalContext();
        String url = extContext.encodeActionURL(extContext.getRequestContextPath() + "/500.xhtml");
        extContext.redirect(url);
      } catch (Exception e) {
        String errorPageLocation = "/WEB-INF/500.xhtml";
        fc.setViewRoot(fc.getApplication().getViewHandler().createView(fc, errorPageLocation));
        fc.getPartialViewContext().setRenderAll(false);
        fc.renderResponse();
      } finally {
        i.remove();
      }
    }

    getWrapped().handle();
  }
Ejemplo n.º 7
0
  public void testTorrent(AjaxBehaviorEvent event) {
    // TODO Это точно такая же часть как и в testMessage
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent component = UIComponent.getCurrentComponent(context);
    String url = (String) ((UIInput) component.findComponent("filmLinkRutracker")).getValue();

    WebBrowser webBrowser = new WebBrowser(LogEnum.WEB.getLog());
    //

    String regexp =
        (String) ((UIInput) component.findComponent("filmRegexpSerialNumber")).getValue();
    FacesMessage message = new FacesMessage();
    try {
      webBrowser.goToUrl(url);
      filmEdit.setTitle(webBrowser.getTitle());
      TorrentFile torrent = webBrowser.downloadTorrentFile(webBrowser.getTorrentUrl());
      ByteArrayInputStream bais = new ByteArrayInputStream(torrent.getContent());
      TorrentInfo info = new TorrentInfo(new BufferedInputStream(bais));
      StringBuilder builder = new StringBuilder();
      for (String fileName : info.getInfo()) {
        builder
            .append(fileName)
            .append(" № серии: \"")
            .append(MessageUtils.parseEpisode(fileName, regexp))
            .append("\"  ");
      }
      message.setSummary(builder.toString());
      message.setSeverity(FacesMessage.SEVERITY_INFO);
    } catch (CoreException e) {
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      message.setSummary(e.getMessage());
    }
    context.addMessage("otherMessageHidden", message);
    context.renderResponse();
  }
Ejemplo n.º 8
0
  @Override
  public void processDecodes(FacesContext context) {
    if (context == null) {
      throw new NullPointerException();
    }

    // Skip processing if our rendered flag is false
    if (!isRendered()) {
      return;
    }

    // XXX: decode component itself first, so that potential submitted
    // value is accurately exposed in context for facets and children
    try {
      decode(context);
    } catch (RuntimeException e) {
      context.renderResponse();
      throw e;
    }

    processFacetsAndChildrenWithVariable(context, PhaseId.APPLY_REQUEST_VALUES);

    if (isImmediate()) {
      executeValidate(context);
    }
  }
 @Override
 public void broadcast(FacesEvent event) throws AbortProcessingException {
   super.broadcast(event);
   if (event instanceof PagerEvent) {
     // Tell JSF to switch to render response, like regular commands
     FacesContext context = getFacesContext();
     context.renderResponse();
   }
 }
Ejemplo n.º 10
0
 public void validateIsEmpty(FacesContext context, UIComponent toValidate, Object value) {
   String newValue = (String) value;
   if (newValue == null || newValue.trim().length() == 0) {
     ((UIInput) toValidate).setValid(false);
     FacesMessage message = new FacesMessage("The field must have a value.");
     context.addMessage(toValidate.getClientId(context), message);
     context.renderResponse();
   }
 }
Ejemplo n.º 11
0
 @Override
 public void broadcast(FacesEvent event) throws AbortProcessingException {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   if (event instanceof ItemChangeEvent) {
     setValue(((ItemChangeEvent) event).getNewItemName());
     setSubmittedActiveItem(null);
     if (event.getPhaseId() == PhaseId.UPDATE_MODEL_VALUES) {
       try {
         updateModel(facesContext);
       } catch (RuntimeException e) {
         facesContext.renderResponse();
         throw e;
       }
     } else {
       facesContext.renderResponse();
     }
   }
   super.broadcast(event);
 }
Ejemplo n.º 12
0
  public static void switchAddImageIntoForm(String formName, String fileName) {

    FacesContext context = FacesContext.getCurrentInstance();

    UIInput txtImageName =
        (UIInput) context.getViewRoot().findComponent(formName + ":txtImageName");
    txtImageName.setValue(fileName);
    txtImageName.setSubmittedValue(fileName);
    context.renderResponse();
  }
Ejemplo n.º 13
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();
 }
Ejemplo n.º 14
0
 public void validateIsEmptyRequiredAffiliation(
     FacesContext context, UIComponent toValidate, Object value) {
   String newValue = (String) value;
   if ((newValue == null || newValue.trim().length() == 0)
       && getVDCRequestBean().getCurrentVdcNetwork().isRequireDVaffiliation()) {
     FacesMessage message = new FacesMessage("The field must have a value.");
     context.addMessage(toValidate.getClientId(context), message);
     context.renderResponse();
     ((UIInput) toValidate).setValid(false);
   }
 }
Ejemplo n.º 15
0
  /**
   * @param context
   * @param resource
   * @throws IOException
   */
  public void send(ResourceContext resourceContext, InternetResource resource) throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (null != facesContext) {
      Lifecycle facesLifecycle = getFacesLifecycle();
      PhaseListener[] phaseListeners = facesLifecycle.getPhaseListeners();
      PhaseEvent restoreViewEvent = new PhaseEvent(facesContext, PhaseId.RESTORE_VIEW, this);
      processPhaseListeners(phaseListeners, restoreViewEvent, true);
      // Fix for a http://jira.jboss.org/jira/browse/RF-1056
      if (facesContext.getResponseComplete()) {
        return;
      }
      // fix for a http://jira.jboss.com/jira/browse/RF-1064 .
      // viewRoot can be created outside.
      UIViewRoot savedViewRoot = facesContext.getViewRoot();
      try {
        // create "dummy" viewRoot, to avoid problems in phase listeners.
        UIViewRoot root = new UIViewRoot();
        String key = resource.getKey();
        if (null != key && !key.startsWith("/")) {
          key = "/" + key;
        }
        root.setViewId(key);
        root.setLocale(Locale.getDefault());
        root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
        facesContext.setViewRoot(root);
        // We do not simulate other phases.
        facesContext.renderResponse();
        // Invoke after restore view phase listeners
        processPhaseListeners(phaseListeners, restoreViewEvent, false);
        // Fix for a http://jira.jboss.org/jira/browse/RF-1056
        if (!facesContext.getResponseComplete()) {
          // Invoke before render view phase listeners
          PhaseEvent renderViewEvent = new PhaseEvent(facesContext, PhaseId.RENDER_RESPONSE, this);

          try {
            processPhaseListeners(phaseListeners, renderViewEvent, true);
            sendResource(resourceContext, resource);
          } finally {
            processPhaseListeners(phaseListeners, renderViewEvent, false);
          }
        }

      } finally {
        if (null != savedViewRoot) {
          facesContext.setViewRoot(savedViewRoot);
        }
      }
    } else {
      sendResource(resourceContext, resource);
    }
  }
Ejemplo n.º 16
0
  public static void switchAddEditBaseForm(String formName, boolean isEdit) {

    FacesContext context = FacesContext.getCurrentInstance();

    UICommand btnAdd = (UICommand) context.getViewRoot().findComponent(formName + ":btnAdd");
    UICommand btnUpdate = (UICommand) context.getViewRoot().findComponent(formName + ":btnUpdate");
    UICommand btnCancel = (UICommand) context.getViewRoot().findComponent(formName + ":btnCancel");

    if (btnAdd != null) btnAdd.setRendered(!isEdit);
    btnUpdate.setRendered(isEdit);
    btnCancel.setRendered(isEdit);

    context.renderResponse();
  }
Ejemplo n.º 17
0
  /**
   * Specialized decode behavior on top of that provided by the superclass. In addition to the
   * standard <code>processDecodes</code> behavior inherited from {@link
   * javax.faces.component.UIComponentBase}, calls <code>processValue()</code> if the the <code>
   * immediate</code> property is true; if the component is invalid afterwards or a <code>
   * RuntimeException</code> is thrown, calls {@link FacesContext#renderResponse}.
   *
   * @throws NullPointerException {@inheritDoc}
   */
  @Override
  public void processDecodes(FacesContext facesContext) {
    if (facesContext == null) {
      throw new NullPointerException();
    }

    // Skip processing if our rendered flag is false
    if (!isRendered()) {
      return;
    }

    pushComponentToEL(facesContext, null);

    final String activeItem = getActiveItemValue();
    EnumSet<VisitHint> hints = EnumSet.of(VisitHint.SKIP_UNRENDERED);
    VisitContext visitContext = new FullVisitContext(facesContext, hints);
    this.visitTree(
        visitContext,
        new VisitCallback() {
          @Override
          public VisitResult visit(VisitContext context, UIComponent target) {
            if (AbstractTogglePanel.this == target || target instanceof UIRepeat) {
              return VisitResult.ACCEPT; // Proceed with visit to target's children
            }
            if (isActiveItem(target, activeItem) || getSwitchType() == SwitchType.client) {
              target.processDecodes(context.getFacesContext());
            }
            return VisitResult
                .REJECT; // No need to visit target's children, as they were recursively visited
                         // above
          }
        });

    // Process this component itself
    try {
      decode(facesContext);
    } catch (RuntimeException e) {
      facesContext.renderResponse();
      throw e;
    } finally {
      popComponentFromEL(facesContext);
    }

    ItemChangeEvent event = createItemChangeEvent(facesContext);
    if (event != null) {
      event.queue();
    }
  }
Ejemplo n.º 18
0
  @Override
  protected void doDecode(FacesContext context, UIComponent component) {
    AbstractTooltip tooltip = (AbstractTooltip) component;

    Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap();

    String compClientId = component.getClientId(context);
    String clientId = requestMap.get(compClientId);
    if (clientId != null && clientId.equals(compClientId)) {
      context.getPartialViewContext().getRenderIds().add(tooltip.getContentClientId(context));

      // TODO nick - this should be done on encode, not on decode
      addOnCompleteParam(context, tooltip.getClientId(context));
      context.renderResponse();
    }
  }
Ejemplo n.º 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();
 }
Ejemplo n.º 20
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();
 }
Ejemplo n.º 21
0
  @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();
    }
  }
Ejemplo n.º 22
0
 public void validateShortDescription(FacesContext context, UIComponent toValidate, Object value) {
   String newValue = (String) value;
   if (newValue != null && newValue.trim().length() > 0) {
     if (newValue.length() > 255) {
       ((UIInput) toValidate).setValid(false);
       FacesMessage message =
           new FacesMessage("The field cannot be more than 255 characters in length.");
       context.addMessage(toValidate.getClientId(context), message);
     }
   }
   if ((newValue == null || newValue.trim().length() == 0)
       && getVDCRequestBean().getCurrentVdcNetwork().isRequireDVdescription()) {
     FacesMessage message = new FacesMessage("The field must have a value.");
     context.addMessage(toValidate.getClientId(context), message);
     ((UIInput) toValidate).setValid(false);
     context.renderResponse();
   }
 }
Ejemplo n.º 23
0
  @Override
  public void handle() throws FacesException {

    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      // get the exception from context
      Throwable t = context.getException();

      final FacesContext fc = FacesContext.getCurrentInstance();
      final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
      final NavigationHandler nav = fc.getApplication().getNavigationHandler();

      // here you do what ever you want with exception
      try {

        if (ExceptionUtils.getRootCause(t) instanceof AccessDeniedException) {
          throw (AccessDeniedException) ExceptionUtils.getRootCause(t);
        }

        log.error("złapano wyjątek: nieprzechwycony przez controller");
        log.error(t.getMessage(), t);
        t.printStackTrace();

        // redirect error page
        requestMap.put("exceptionMessage", t.getMessage());
        nav.handleNavigation(fc, null, "/error");
        fc.renderResponse();

        // remove the comment below if you want to report the error in a jsf error message
        //                JsfUtil.addErrorMessage(t.getMessage());

      } finally {
        // remove it from queue
        i.remove();
      }
    }
    // parent hanle
    getWrapped().handle();
  }
Ejemplo n.º 24
0
  public void validateName(FacesContext context, UIComponent toValidate, Object value) {
    String name = (String) value;
    if (name != null && name.trim().length() == 0) {
      FacesMessage message = new FacesMessage("The dataverse name field must have a value.");
      context.addMessage(toValidate.getClientId(context), message);
      context.renderResponse();
    }
    boolean nameFound = false;
    VDC vdc = vdcService.findByName(name);
    if (vdc != null) {
      nameFound = true;
    }
    if (nameFound) {
      ((UIInput) toValidate).setValid(false);

      FacesMessage message = new FacesMessage("This name is already taken.");
      context.addMessage(toValidate.getClientId(context), message);
    }

    resetScholarProperties();
  }
Ejemplo n.º 25
0
  // Multi field validation with <f:event>
  // Rule: first two digits of PIN must match last two digits of the year of
  // birth
  public void validatePinDob(ComponentSystemEvent event) {

    UIForm form = (UIForm) event.getComponent();
    UIInput pin = (UIInput) form.findComponent("zip");
    UIInput dob = (UIInput) form.findComponent("zip");

    if (pin.getValue() != null
        && dob.getValue() != null
        && pin.getValue().toString().length() >= 2) {
      String twoDigitsOfPin = pin.getValue().toString().substring(0, 2);
      Calendar cal = Calendar.getInstance();
      cal.setTime(((Date) dob.getValue()));

      String lastDigitsOfDob = ((Integer) cal.get(Calendar.YEAR)).toString().substring(2);

      if (!twoDigitsOfPin.equals(lastDigitsOfDob)) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(form.getClientId(), new FacesMessage("PIN doesn't match date of birth"));
        context.renderResponse();
      }
    }
  }
 @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);
     }
   }
 }
Ejemplo n.º 27
0
  public void testMessage(AjaxBehaviorEvent event) {
    FacesContext context = FacesContext.getCurrentInstance();
    UIComponent component = UIComponent.getCurrentComponent(context);
    String url = (String) ((UIInput) component.findComponent("filmLinkRutracker")).getValue();

    WebBrowser webBrowser = new WebBrowser(LogEnum.WEB.getLog());
    FacesMessage message = new FacesMessage();
    try {
      webBrowser.goToUrl(url);
      String title = webBrowser.getTitle();
      filmEdit.setTitle(title);
      String regexp = (String) ((UIInput) component.findComponent("filmMailRegexp")).getValue();
      String mailMessage =
          (String) ((UIInput) component.findComponent("filmMailMessage")).getValue();
      message.setSummary(MessageUtils.createMessage(title, regexp, mailMessage));
      message.setSeverity(FacesMessage.SEVERITY_INFO);
    } catch (CoreException e) {
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      message.setSummary(e.getMessage());
    }
    context.addMessage("otherMessageHidden", message);
    context.renderResponse();
  }
  @Override
  protected void doDecode(FacesContext context, UIComponent component) {
    AbstractAutocomplete autocomplete = (AbstractAutocomplete) component;
    if (InputUtils.isDisabled(autocomplete)) {
      return;
    }
    Map<String, String> requestParameters = context.getExternalContext().getRequestParameterMap();
    String value = requestParameters.get(component.getClientId(context) + "Input");
    if (value != null) {
      autocomplete.setSubmittedValue(value);
    }

    if (requestParameters.get(component.getClientId(context) + ".ajax") != null) {
      PartialViewContext pvc = context.getPartialViewContext();
      pvc.getRenderIds()
          .add(
              component.getClientId(context)
                  + MetaComponentResolver.META_COMPONENT_SEPARATOR_CHAR
                  + AbstractAutocomplete.ITEMS_META_COMPONENT_ID);

      context.renderResponse();
    }
  }
Ejemplo n.º 29
0
  private void updateModel(int newPage) {

    FacesContext facesContext = getFacesContext();
    UIComponent dataTable = getDataTable();

    if (isRendered(dataTable)) {
      dataTable.getAttributes().put("first", (newPage - 1) * getRows(dataTable));
    }

    Map<String, Object> attributes = dataTable.getAttributes();
    attributes.put(dataTable.getClientId(facesContext) + SCROLLER_STATE_ATTRIBUTE, newPage);

    ValueExpression ve = getValueExpression("page");
    if (ve != null) {
      try {
        ve.setValue(facesContext.getELContext(), newPage);
        attributes.remove(dataTable.getClientId(facesContext) + SCROLLER_STATE_ATTRIBUTE);
      } catch (ELException e) {
        String messageStr = e.getMessage();
        Throwable result = e.getCause();
        while (null != result && result.getClass().isAssignableFrom(ELException.class)) {
          messageStr = result.getMessage();
          result = result.getCause();
        }
        FacesMessage message;
        if (null == messageStr) {
          message =
              ServiceTracker.getService(MessageFactory.class)
                  .createMessage(
                      facesContext,
                      FacesMessages.UIINPUT_UPDATE,
                      MessageUtil.getLabel(facesContext, this));
        } else {
          message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr);
        }
        facesContext.getExternalContext().log(message.getSummary(), result);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      } catch (IllegalArgumentException e) {
        FacesMessage message =
            ServiceTracker.getService(MessageFactory.class)
                .createMessage(
                    facesContext,
                    FacesMessages.UIINPUT_UPDATE,
                    MessageUtil.getLabel(facesContext, this));
        facesContext.getExternalContext().log(message.getSummary(), e);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      } catch (Exception e) {
        FacesMessage message =
            ServiceTracker.getService(MessageFactory.class)
                .createMessage(
                    facesContext,
                    FacesMessages.UIINPUT_UPDATE,
                    MessageUtil.getLabel(facesContext, this));
        facesContext.getExternalContext().log(message.getSummary(), e);
        facesContext.addMessage(getClientId(facesContext), message);
        facesContext.renderResponse();
      }
    }
  }
Ejemplo n.º 30
0
  /**
   * PRECONDITION: the necessary factories have been installed in the ServletContext attr set.
   *
   * <p>
   *
   * <p>POSTCONDITION: The facesContext has been initialized with a tree.
   */
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RestoreViewPhase");
    }
    if (null == facesContext) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_CONTEXT_ERROR_MESSAGE_ID));
    }

    // If an app had explicitely set the tree in the context, use that;
    //
    UIViewRoot viewRoot = facesContext.getViewRoot();
    if (viewRoot != null) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Found a pre created view in FacesContext");
      }
      facesContext.getViewRoot().setLocale(facesContext.getExternalContext().getRequestLocale());

      // do per-component actions
      UIViewRoot root = facesContext.getViewRoot();
      final PostRestoreStateEvent event = new PostRestoreStateEvent(root);
      try {
        root.visitTree(
            VisitContext.createVisitContext(facesContext),
            new VisitCallback() {

              public VisitResult visit(VisitContext context, UIComponent target) {
                event.setComponent(target);
                target.processEvent(event);
                return VisitResult.ACCEPT;
              }
            });
      } catch (AbortProcessingException e) {
        facesContext
            .getApplication()
            .publishEvent(
                ExceptionQueuedEvent.class, new ExceptionQueuedEventContext(facesContext, e));
      }

      if (!facesContext.isPostback()) {
        facesContext.renderResponse();
      }
      return;
    }

    // Reconstitute or create the request tree
    Map requestMap = facesContext.getExternalContext().getRequestMap();
    String viewId = (String) requestMap.get("javax.servlet.include.path_info");
    if (viewId == null) {
      viewId = facesContext.getExternalContext().getRequestPathInfo();
    }

    // It could be that this request was mapped using
    // a prefix mapping in which case there would be no
    // path_info.  Query the servlet path.
    if (viewId == null) {
      viewId = (String) requestMap.get("javax.servlet.include.servlet_path");
    }

    if (viewId == null) {
      viewId = facesContext.getExternalContext().getRequestServletPath();
    }

    if (viewId == null) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning("viewId is null");
      }
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_REQUEST_VIEW_ERROR_MESSAGE_ID));
    }

    ViewHandler viewHandler = Util.getViewHandler(facesContext);

    boolean isPostBack = (facesContext.isPostback() && !isErrorPage(facesContext));
    if (isPostBack) {
      // try to restore the view
      viewRoot = viewHandler.restoreView(facesContext, viewId);
      if (viewRoot == null) {
        if (is11CompatEnabled(facesContext)) {
          // 1.1 -> create a new view and flag that the response should
          //        be immediately rendered
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Postback: recreating a view for " + viewId);
          }
          viewRoot = viewHandler.createView(facesContext, viewId);
          facesContext.renderResponse();

        } else {
          Object[] params = {viewId};
          throw new ViewExpiredException(
              MessageUtils.getExceptionMessageString(
                  MessageUtils.RESTORE_VIEW_ERROR_MESSAGE_ID, params),
              viewId);
        }
      }

      facesContext.setViewRoot(viewRoot);

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Postback: restored view for " + viewId);
      }
    } else {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("New request: creating a view for " + viewId);
      }

      ViewDeclarationLanguage vdl =
          facesContext
              .getApplication()
              .getViewHandler()
              .getViewDeclarationLanguage(facesContext, viewId);

      if (vdl != null) {
        // If we have one, get the ViewMetadata...
        ViewMetadata metadata = vdl.getViewMetadata(facesContext, viewId);

        if (metadata != null) { // perhaps it's not supported
          // and use it to create the ViewRoot.  This will have, at most
          // the UIViewRoot and its metadata facet.
          viewRoot = metadata.createMetadataView(facesContext);

          // Only skip to render response if there are no view parameters
          Collection<UIViewParameter> params = ViewMetadata.getViewParameters(viewRoot);
          if (params.isEmpty()) {
            facesContext.renderResponse();
          }
        }
      } else {
        facesContext.renderResponse();
      }

      if (null == viewRoot) {
        viewRoot = (Util.getViewHandler(facesContext)).createView(facesContext, viewId);
      }
      facesContext.setViewRoot(viewRoot);
      assert (null != viewRoot);
      facesContext.getApplication().publishEvent(PostAddToViewEvent.class, viewRoot);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RestoreViewPhase");
    }
  }