public void salir() {
    try {
      System.out.println("entre a CONTROLBETACENTROSCOSTOS.Salir");
      FacesContext c = FacesContext.getCurrentInstance();
      if (bandera == 1) {
        fechaInicial = (Column) c.getViewRoot().findComponent("form:datosEmpresas:fechaInicial");
        fechaInicial.setFilterStyle("display: none; visibility: hidden;");
        fechaFinal = (Column) c.getViewRoot().findComponent("form:datosEmpresas:fechaFinal");
        fechaFinal.setFilterStyle("display: none; visibility: hidden;");

        tamano = 260;
        bandera = 0;
        filtrarEmpresas = null;
        tipoLista = 0;
      }

      modificarEmpresas.clear();
      index = -1;
      k = 0;
      listEmpresa = null;
      guardado = true;
      permitirIndex = true;
      RequestContext context = RequestContext.getCurrentInstance();
      context.update("form:datosEmpresas");
      context.update("form:ACEPTAR");
      context.update("formularioDialogos:aceptarE");

    } catch (Exception E) {
      System.out.println(
          "ERROR CONTROLBETACENTROSCOSTOS.ModificarModificacion ERROR===================="
              + E.getMessage());
    }
  }
  /**
   * Creates and returns a FacesMessage for the specified Locale.
   *
   * @param context - the <code>FacesContext</code> for the current request
   * @param messageId - the key of the message in the resource bundle
   * @param params - substittion parameters
   * @return a localized <code>FacesMessage</code> with the severity of FacesMessage.SEVERITY_ERROR
   */
  protected static FacesMessage getMessage(
      FacesContext context, String messageId, Object... params) {

    if (context == null || messageId == null) {
      throw new NullPointerException(" context " + context + " messageId " + messageId);
    }
    Locale locale;
    // viewRoot may not have been initialized at this point.
    if (context.getViewRoot() != null) {
      locale = context.getViewRoot().getLocale();
    } else {
      locale = Locale.getDefault();
    }

    if (null == locale) {
      throw new NullPointerException(" locale is null ");
    }

    FacesMessage message = getMessage(locale, messageId, params);
    if (message != null) {
      return message;
    }
    locale = Locale.getDefault();
    return (getMessage(locale, messageId, params));
  }
Example #3
0
  public void render(FacesContext context) throws FacesException {
    if (context.getResponseComplete()) return;

    Application app = context.getApplication();
    ViewHandler view = app.getViewHandler();

    beforePhase(context, PhaseId.RENDER_RESPONSE);

    try {
      if (log.isLoggable(Level.FINER)) log.finer(context.getViewRoot() + " before render view");

      view.renderView(context, context.getViewRoot());
    } catch (java.io.IOException e) {
      if (sendError(context, "renderView", e)) return;

      throw new FacesException(e);
    } catch (RuntimeException e) {
      if (sendError(context, "renderView", e)) return;

      throw e;
    } finally {
      afterPhase(context, PhaseId.RENDER_RESPONSE);

      logMessages(context);
    }
  }
Example #4
0
  //
  // Event processing: Creates a datatable and adds a component to it.
  //
  @Override
  public void processEvent(SystemEvent event) throws AbortProcessingException {
    FacesContext context = FacesContext.getCurrentInstance();
    if (!context.isPostback()) {
      Application application = context.getApplication();

      HtmlDataTable dataTable = new HtmlDataTable();
      dataTable.setVar("_internal");
      dataTable.setValueExpression(
          "value",
          application
              .getExpressionFactory()
              .createValueExpression(context.getELContext(), "#{addBean.list}", Object.class));
      getChildren().add(dataTable);

      UIColumn column = new UIColumn();
      column.setId(context.getViewRoot().createUniqueId());
      dataTable.getChildren().add(column);

      HtmlOutputText outputText = new HtmlOutputText();
      outputText.setId(context.getViewRoot().createUniqueId());
      outputText.setValueExpression(
          "value",
          application
              .getExpressionFactory()
              .createValueExpression(context.getELContext(), "#{_internal}", Object.class));
      column.getChildren().add(outputText);
    }
  }
Example #5
0
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RenderResponsePhase");
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("About to render view " + facesContext.getViewRoot().getViewId());
    }
    // For requests intended to produce a partial response, we need prohibit
    // writing any content outside of the view itself (f:view).
    PartialViewContext partialViewContext = facesContext.getPartialViewContext();
    if (partialViewContext.isAjaxRequest()) {
      OnOffResponseWrapper onOffResponse = new OnOffResponseWrapper(facesContext);
      onOffResponse.setEnabled(false);
    }

    try {

      ViewHandler vh = facesContext.getApplication().getViewHandler();

      ViewDeclarationLanguage vdl =
          vh.getViewDeclarationLanguage(facesContext, facesContext.getViewRoot().getViewId());
      if (vdl != null) {
        vdl.buildView(facesContext, facesContext.getViewRoot());
      }

      boolean viewIdsUnchanged;
      do {
        String beforePublishViewId = facesContext.getViewRoot().getViewId();
        // the before render event on the view root is a special case to keep door open for
        // navigation
        // this must be called *after* PDL.buildView() and before VH.renderView()
        facesContext
            .getApplication()
            .publishEvent(facesContext, PreRenderViewEvent.class, facesContext.getViewRoot());
        String afterPublishViewId = facesContext.getViewRoot().getViewId();
        viewIdsUnchanged =
            beforePublishViewId == null && afterPublishViewId == null
                || (beforePublishViewId != null && afterPublishViewId != null)
                    && beforePublishViewId.equals(afterPublishViewId);
      } while (!viewIdsUnchanged);

      // render the view
      vh.renderView(facesContext, facesContext.getViewRoot());

    } catch (IOException e) {
      throw new FacesException(e.getMessage(), e);
    }

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.log(
          Level.FINEST,
          "+=+=+=+=+=+= View structure printout for " + facesContext.getViewRoot().getViewId());
      DebugUtil.printTree(facesContext.getViewRoot(), LOGGER, Level.FINEST);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RenderResponsePhase");
    }
  }
  public static Optional<String> getLocalePrefixForLocateResource(final FacesContext facesContext) {
    String localePrefix = null;
    boolean isResourceRequest =
        facesContext.getApplication().getResourceHandler().isResourceRequest(facesContext);

    if (isResourceRequest) {
      localePrefix =
          facesContext
              .getExternalContext()
              .getRequestParameterMap()
              .get(OsgiResource.REQUEST_PARAM_LOCALE);

      if (localePrefix != null) {
        if (!ResourceValidationUtils.isValidLocalePrefix(localePrefix)) {
          return Optional.empty();
        }
        return Optional.of(localePrefix);
      }
    }

    String bundleName = facesContext.getApplication().getMessageBundle();

    if (null != bundleName) {
      Locale locale = null;

      if (isResourceRequest || facesContext.getViewRoot() == null) {
        locale = facesContext.getApplication().getViewHandler().calculateLocale(facesContext);
      } else {
        locale = facesContext.getViewRoot().getLocale();
      }

      try {
        // load resource via ServletContext because due to Classloader
        ServletContext servletContext =
            (ServletContext) facesContext.getExternalContext().getContext();
        PropertyResourceBundle resourceBundle = null;
        try {
          URL resourceUrl =
              servletContext.getResource(
                  '/' + bundleName.replace('.', '/') + '_' + locale + ".properties");
          if (resourceUrl != null) {
            resourceBundle = new PropertyResourceBundle(resourceUrl.openStream());
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
        if (resourceBundle != null) {
          localePrefix = resourceBundle.getString(ResourceHandler.LOCALE_PREFIX);
        }
      } catch (MissingResourceException e) {
        // Ignore it and return null
      }
    }
    return Optional.ofNullable(localePrefix);
  }
  public void cancelarModificacion() {
    try {
      System.out.println("entre a CONTROLBETACENTROSCOSTOS.cancelarModificacion");
      FacesContext c = FacesContext.getCurrentInstance();
      if (bandera == 1) {
        // CERRAR FILTRADO
        // 0
        fechaInicial = (Column) c.getViewRoot().findComponent("form:datosEmpresas:fechaInicial");
        fechaInicial.setFilterStyle("display: none; visibility: hidden;");
        // 1
        fechaFinal = (Column) c.getViewRoot().findComponent("form:datosEmpresas:fechaFinal");
        fechaFinal.setFilterStyle("display: none; visibility: hidden;");

        tamano = 260;
        bandera = 0;
        filtrarEmpresas = null;
        tipoLista = 0;
      }

      modificarEmpresas.clear();
      index = -1;
      k = 0;
      listEmpresa = null;
      guardado = true;
      permitirIndex = true;
      buscarCentrocosto = false;
      mostrartodos = true;
      RequestContext context = RequestContext.getCurrentInstance();
      banderaModificacionEmpresa = 0;
      if (banderaModificacionEmpresa == 0) {
        cambiarEmpresa();
      }
      getListEmpresa();
      if (listEmpresa == null || listEmpresa.isEmpty()) {
        infoRegistro = "Cantidad de registros: 0 ";
      } else {
        infoRegistro = "Cantidad de registros: " + listEmpresa.size();
      }
      context.update("form:informacionRegistro");
      context.update("form:datosEmpresas");
      context.update("form:ACEPTAR");
      context.update("form:BUSCARCENTROCOSTO");
      context.update("form:MOSTRARTODOS");
      context.update("formularioDialogos:aceptarE");

    } catch (Exception E) {
      System.out.println(
          "ERROR CONTROLBETACENTROSCOSTOS.ModificarModificacion ERROR===================="
              + E.getMessage());
    }
  }
Example #8
0
 public static Locale getLocale() {
   // for JSF Context
   FacesContext facesContext = FacesContext.getCurrentInstance();
   if (facesContext != null) {
     if (facesContext.getViewRoot() != null) {
       return facesContext.getViewRoot().getLocale();
     }
     if (facesContext.getApplication() != null
         && facesContext.getApplication().getDefaultLocale() != null) {
       return facesContext.getApplication().getDefaultLocale();
     }
   }
   return ResourceBundleUtils.PT_BR;
 }
  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();
  }
Example #10
0
  /**
   * This version of getMessage() is used for localizing implementation specific messages.
   *
   * @param messageId - the key of the message in the resource bundle
   * @param params - substittion parameters
   * @return a localized <code>FacesMessage</code> with the severity of FacesMessage.SEVERITY_ERROR
   */
  public static FacesMessage getMessage(String messageId, Object... params) {
    Locale locale = null;
    FacesContext context = FacesContext.getCurrentInstance();
    // context.getViewRoot() may not have been initialized at this point.
    if (context != null && context.getViewRoot() != null) {
      locale = context.getViewRoot().getLocale();
      if (locale == null) {
        locale = Locale.getDefault();
      }
    } else {
      locale = Locale.getDefault();
    }

    return getMessage(locale, messageId, params);
  }
Example #11
0
  public String adminAddSuccessAction() {
    if (areaSelectName == null) {
      FacesContext context = FacesContext.getCurrentInstance();
      String bundleName = context.getApplication().getMessageBundle();
      ResourceBundle messageBundle =
          ResourceBundle.getBundle(
              bundleName,
              context.getViewRoot().getLocale(),
              Thread.currentThread().getContextClassLoader());
      String prompt = messageBundle.getString("selectArea");

      FacesUtils.addErrorMessage(prompt);
      return null;
    } else {
      Administrator admin = new Administrator();
      String condition = " name ='" + this.areaSelectName + "'";
      area_admin = this.serviceLocator.getAreaService().queryAreaByCondition(condition).get(0);
      admin.setAdr(adr_admin);
      admin.setArea(area_admin);
      admin.setEmail(email_admin);
      admin.setName(name_admin);
      admin.setTel(tel_admin);
      this.serviceLocator.getAdminService().saveAdministrator(admin);
      return NavigationResults.ADMINADDSUCCESSACTION;
    }
  }
Example #12
0
  public String areaAddSuccessAction() {
    Area area = new Area();
    if ((areaSelectName == null) || (areaSelectName.equals(""))) {
      // superiorArea = 0;
      FacesContext context = FacesContext.getCurrentInstance();
      String bundleName = context.getApplication().getMessageBundle();
      ResourceBundle messageBundle =
          ResourceBundle.getBundle(
              bundleName,
              context.getViewRoot().getLocale(),
              Thread.currentThread().getContextClassLoader());
      String prompt = messageBundle.getString("selectSuperArea");

      FacesUtils.addErrorMessage(prompt);
      return null;
    } else {
      String condition = "name ='" + this.areaSelectName + "'";
      superiorArea =
          this.serviceLocator.getAreaService().queryAreaByCondition(condition).get(0).getAreaId();

      area.setSuperiorArea(superiorArea);
      area.setName(name);
      area.setIntro(intro);
      area.setPrincipal(principal);
      area.setTel(tel);
      area.setCoordinateX(coordinateX);
      area.setCoordinateY(coordinateY);
      this.serviceLocator.getAreaService().saveArea(area);
      return NavigationResults.AREAADDSUCCESSACTION;
    }
  }
  public ComponentWrapper startElement(
      FacesContext context,
      ComponentWrapper parent,
      String uri,
      String localName,
      String qName,
      Attributes attributes)
      throws IOException {
    UIViewRoot root = context.getViewRoot();
    HtmlOutputLink link =
        (HtmlOutputLink) context.getApplication().createComponent(HtmlOutputLink.COMPONENT_TYPE);
    link.setId(root.createUniqueId());
    parent.getComponent().getChildren().add(link);

    link.setTarget("_parent");
    ToolCategoryComponent parentCategoryComponent = findParentCategory(parent);
    ToolComponent parentComponent = findParentTool(parent);

    if (parentComponent.getPage() != null) {
      // Resolve the site_type of the form /portal/category/<siteId>/<categoryKey>/<optionalToolId>
      String url =
          parentCategoryComponent.getContext()
              + "/category/"
              + parentCategoryComponent.getSiteId()
              + "/"
              + parentCategoryComponent.getToolCategory().getKey()
              + "/"
              + parentComponent.getPage().getId();
      link.setValue(url);
    }
    return new ComponentWrapper(parent, link, this);
  }
  @Override
  public VisitContext getVisitContext(
      FacesContext facesContext, Collection<String> ids, Set<VisitHint> hints) {

    // Prepend the ids with the portlet namespace unless they already start with the namespace, or
    // if the id starts with the SeparatorChar
    if (ids != null) {

      UIViewRoot viewRoot = facesContext.getViewRoot();
      String separator = String.valueOf(UINamingContainer.getSeparatorChar(facesContext));
      String containerClientIdAndSeparator =
          viewRoot.getContainerClientId(facesContext) + separator;

      List<String> newIds = new ArrayList<String>();

      for (String id : ids) {

        if (!id.startsWith(separator) && !id.startsWith(containerClientIdAndSeparator)) {
          id = containerClientIdAndSeparator + id;
        }

        newIds.add(id);
      }

      ids = newIds;
    }

    return wrappedVisitContextFactory.getVisitContext(facesContext, ids, hints);
  }
 /**
  * Metodo que busca una historia clinica
  *
  * @author David Carranza
  */
 public void buscarListado() {
   String nombreMetodo = Thread.currentThread().getStackTrace()[1].getMethodName() + "()";
   FacesContext context = FacesContext.getCurrentInstance();
   try {
     lista = new ArrayList<>();
     lista =
         admin.listarOrdenada(
             object.getClass(),
             "cplFechaMuestra",
             fechaInicio,
             "cplEstado",
             3,
             "cplOrdenLlegada",
             true);
     if (lista.isEmpty()) {
       FacesContext.getCurrentInstance()
           .addMessage(
               findComponent(context.getViewRoot(), "formDatos").getClientId(),
               new FacesMessage(
                   FacesMessage.SEVERITY_ERROR,
                   "Busqueda sin resultados",
                   "No se encontro paciente"));
     }
   } catch (Exception e) {
     log.error("{}: {} ", nombreMetodo, e);
   }
 }
 /* (non-Javadoc)
  * @see com.code.aon.ui.form.event.ControllerAdapter#beforeBeanUpdated(com.code.aon.ui.form.event.ControllerEvent)
  */
 @Override
 public void beforeBeanUpdated(ControllerEvent event) throws ControllerListenerException {
   UserController uc = (UserController) event.getController();
   User user = (User) uc.getTo();
   UserManager userManager = uc.getUserManager();
   String name = user.getName();
   name = (name.equals(userManager.getUser().getName())) ? userManager.getUser().getName() : name;
   String password = userManager.getPassword();
   if (password == null
       || password.equals("")
       || password.equals(userManager.getUser().getPasswd())) {
     userManager.setChangePassword(false);
   } else {
     userManager.setChangePassword(true);
   }
   userManager.setName(name);
   try {
     userManager.accept(null);
     user.setLogin(userManager.getId());
   } catch (MaximumLoginException e) {
     FacesContext ctx = FacesContext.getCurrentInstance();
     ResourceBundle bundle =
         ResourceBundle.getBundle(IOperation.MESSAGES_FILE, ctx.getViewRoot().getLocale());
     MessageFormat mf = new MessageFormat(bundle.getString(e.getMessage()));
     throw new ControllerListenerException(mf.format(new Object[] {e.getArg()}), e);
   }
 }
Example #17
0
 public static void refresh() {
   FacesContext context = FacesContext.getCurrentInstance();
   Application application = context.getApplication();
   ViewHandler viewHandler = application.getViewHandler();
   UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
   context.setViewRoot(viewRoot);
 }
Example #18
0
 private String generateCliendId(FacesContext context) {
   NamingContainer namingContainer = FacesUtils.findParentOfType(this, NamingContainer.class);
   if (namingContainer != null && namingContainer instanceof UniqueIdVendor) {
     return ((UniqueIdVendor) namingContainer).createUniqueId(context, null);
   }
   return context.getViewRoot().createUniqueId();
 }
Example #19
0
  /**
   * Renders the Javascript code dealing with the click event. If the developer provides their own
   * onclick handler, is precedes the generated Javascript code.
   *
   * @param context The current FacesContext.
   * @param attrs the attribute list
   * @return some Javascript code, such as "window.location.href='/targetView.jsf';"
   */
  private String encodeClick(FacesContext context, Map<String, Object> attrs) {
    String js;
    String userClick = getOnclick();
    if (userClick != null) {
      js = userClick;
    } // +COLON; }
    else {
      js = "";
    }

    String fragment = asString(attrs.get(FRAGMENT));
    String outcome = getOutcome();

    if (canOutcomeBeRendered(attrs, fragment, outcome)) {
      outcome = (outcome == null) ? context.getViewRoot().getViewId() : outcome;

      String url = determineTargetURL(context, outcome);

      if (url != null) {
        if (fragment != null) {
          url += "#" + fragment;
        }
        js += "window.location.href='" + url + "';";
      }
    }

    return js;
  }
  @Override
  protected void encodeHiddenAttributes(
      FacesContext facesContext, ResponseWriter responseWriter, InputFile inputFile, boolean first)
      throws IOException {

    // fileFieldName
    encodeString(responseWriter, "fileFieldName", inputFile.getClientId(), first);
    first = false;

    // multipleFiles
    String multiple = inputFile.getMultiple();
    boolean multipleFiles = "multiple".equalsIgnoreCase(multiple);
    encodeBoolean(responseWriter, "multipleFiles", multipleFiles, first);

    // selectFilesButton
    Locale locale = facesContext.getViewRoot().getLocale();
    String chooseFiles = getMessageContext().getMessage(locale, "choose-files");
    StringBuilder selectFilesButtonScript = new StringBuilder();
    selectFilesButtonScript.append(
        "A.Node.create(\"<button type='button' class='alloy-button' role='button' aria-label='");
    selectFilesButtonScript.append(chooseFiles);
    selectFilesButtonScript.append("' tabindex='{tabIndex}'>");
    selectFilesButtonScript.append(chooseFiles);
    selectFilesButtonScript.append("</button>\")");
    encodeNonEscapedObject(responseWriter, "selectFilesButton", selectFilesButtonScript, first);
  }
Example #21
0
  /**
   * @param ctx FacesContext.
   * @param viewId the view ID to check or null if viewId is unknown.
   * @return <code>true</code> if partial state saving should be used for the specified view ID,
   *     otherwise <code>false</code>
   */
  public boolean isPartialStateSaving(FacesContext ctx, String viewId) {
    // track UIViewRoot changes
    UIViewRoot root = ctx.getViewRoot();
    UIViewRoot refRoot = viewRootRef.get();
    if (root != refRoot) {
      // set weak reference to current viewRoot
      this.viewRootRef = new WeakReference<UIViewRoot>(root);

      // On first call in restore phase, viewRoot is null, so we treat the first
      // change to not null not as a changing viewRoot.
      if (refRoot != null) {
        // view root changed in request processing - force usage of a
        // new AddRemoveListener instance for the new viewId ...
        modListener = null;
        // ... and also force check for partial state saving for the new viewId
        partialLocked = false;
      }
    }

    if (!partialLocked) {
      if (viewId == null) {
        if (root != null) {
          viewId = root.getViewId();
        } else {
          // View root has not yet been initialized.  Check to see whether
          // the target view id has been stashed away for us.
          viewId = (String) ctx.getAttributes().get(RIConstants.VIEWID_KEY_NAME);
        }
      }

      partial = stateInfo.usePartialStateSaving(viewId);
      partialLocked = true;
    }
    return partial;
  }
  /*
   * (non-Javadoc)
   *
   * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
   */
  public void afterPhase(PhaseEvent event) {
    try {
      FacesContext context = event.getFacesContext();

      // can't use this here. only valid at render response phase?
      String viewId = context.getViewRoot().getViewId();
      AccessLevel required = requiredLevel(viewId);
      log.debug("Required level={} for viewId={}", required, viewId);

      // check if page require access:
      switch (required) {
        case NONE:
          break;
        case ADMIN:
          redirectAdmin(event.getFacesContext());
          break;
        case CLIENT:
          redirectClient(event.getFacesContext());
          break;
        default:
          // error
          log.error("huh?");
          throw new IllegalArgumentException("Not a valid access level");
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      log.error("beforePhase caught exception", e);
    }
  }
  /**
   * This method is called before the {@link PhaseId#INVOKE_APPLICATION} phase of the JSF lifecycle
   * is executed. The purpose of this timing is to handle the case when the user clicks on a {@link
   * UICommand} component (like h:commandButton or h:commandLink) that has been either
   * Auto-ajaxified by ICEfaces, or manually Ajaxified by the developer using code like the
   * following:
   *
   * <p><code>&lt;f:ajax execute="@form" render=" @form" /&gt;</code>
   *
   * <p>When this happens, we need to somehow remember the list of JavaScript and/or CSS resources
   * that are currently in the &lt;head&gt; section of the portal page. This is because a
   * navigation-rule might fire which could cause a new view to be rendered in the {@link
   * PhaseId#RENDER_RESPONSE} phase that is about to follow this {@link PhaseId#INVOKE_APPLICATION}
   * phase. The list of resources would be contained in the {@link HeadManagedBean} {@link
   * ViewScoped} instance that is managed by the JSF managed-bean facility. The list would have been
   * populated initially in the {@link HeadManagedBean} by the {@link HeadRender} during the initial
   * HTTP-GET of the portal page. The way we "remember" the list is by placing it into the JSF 2
   * {@link Flash} scope. This scope is used because it is very short-lived and survives any
   * navigation-rules that might fire, thereby causing the rendering of a new JSF view.
   *
   * <p>The story is continued in the {@link #beforeRenderResponsePhase(PhaseEvent)} method below...
   */
  protected void beforeInvokeApplicationPhase(PhaseEvent phaseEvent) {

    // Get the list of resourceIds that might be contained in the Flash scope. Note that they would
    // have been
    // placed into the Flash scope by this very same method, except during in the case below for the
    // RENDER_RESPONSE phase.
    FacesContext facesContext = phaseEvent.getFacesContext();
    Flash flash = facesContext.getExternalContext().getFlash();

    @SuppressWarnings("unchecked")
    Set<String> headResourceIdsFromFlash = (Set<String>) flash.get("HEAD_RESOURCE_IDS");

    // Log the viewId so that it can be visually compared with the value that is to be logged after
    // the
    // INVOKE_APPLICATION phase completes.
    logger.debug("Before INVOKE_APPLICATION: viewId=[{0}]", facesContext.getViewRoot().getViewId());

    // If the Flash scope does not yet contain a list of head resourceIds, then the scope needs to
    // be populated
    // with a list so that the {@link #beforeRenderResponsePhase(PhaseEvent)} method below can
    // retrieve it.
    if (headResourceIdsFromFlash == null) {

      HeadManagedBean headManagedBean = HeadManagedBean.getInstance(facesContext);

      // Note that in the case where a portlet RESOURCE_PHASE was invoked with a "portlet:resource"
      // type of URL,
      // there will be no HeadManagedBean available.
      if (headManagedBean != null) {
        flash.put("HEAD_RESOURCE_IDS", headManagedBean.getHeadResourceIds());
      }
    }
  }
 public void validateEndDate(FacesContext context, UIComponent component, Object value)
     throws ValidatorException {
   Date endDate = (Date) value;
   if (endDate == null) {
     ZVotesUtils.throwValidatorException("EndDateNotSet");
   }
   UIInput startDateComponent =
       (UIInput) (context.getViewRoot().findComponent("pollEditForm:startDate"));
   Date startDate = (Date) startDateComponent.getValue();
   if (startDate.after(endDate)) {
     ZVotesUtils.throwValidatorException("EndDateBeforeStartDate");
   }
   if (endDate.before(new Date())) {
     ZVotesUtils.throwValidatorException("EndDateBeforeNow");
   }
   if (current.getId() != null) {
     Date previousEndDate = getFacade().find(current.getId()).getEndDate();
     if ((current.getPollState().equals(PollState.PUBLISHED)
             || current.getPollState().equals(PollState.STARTED)
             || current.getPollState().equals(PollState.VOTING))
         && endDate.before(previousEndDate)) {
       ZVotesUtils.throwValidatorException("EndDateCantBeMovedToEarlierTime");
     }
   }
 }
 public String process() {
   if (!this.loggedIn) {
     try {
       this.loggedIn =
           this.authenticateObject.check(new AuthenticateDTO(this.login, this.password));
     } catch (EJBException ejbex) {
       this.loggedIn = false;
       System.out.println(ejbex.toString());
     }
   } else {
     this.loggedIn = false;
   }
   if (this.loggedIn) {
     ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
         .getSession(true);
     this.cartObject.initialize();
   } else {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     ExternalContext externalContext = facesContext.getExternalContext();
     Locale loc = externalContext.getRequestLocale();
     externalContext.invalidateSession();
     facesContext.getViewRoot().setLocale(loc);
     if (this.cartObject != null) {
       this.cartObject.setClientId(null);
       this.cartObject.setMerchandiseId(null);
       this.cartObject.setAmount(null);
       this.cartObject.destroy();
     }
     this.currencyObject.setLocalizationLocale(loc);
   }
   return null;
 }
Example #26
0
 public static Locale getLocale(FacesContext context) {
   Locale locale = null;
   UIViewRoot viewRoot = context.getViewRoot();
   if (viewRoot != null) locale = viewRoot.getLocale();
   if (locale == null) locale = Locale.getDefault();
   return locale;
 }
  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();
      }
    }
  }
  public static void setLocale(FacesContext context, Locale locale) {

    UIViewRoot viewRoot = context.getViewRoot();
    if (viewRoot != null) {
      viewRoot.setLocale(locale);
    }
  }
  /**
   * Apply Request Values (JSF.2.2.2)
   *
   * @param viewId The view id
   * @param facesContext The faces context
   * @return true, if response is complete
   */
  protected boolean executePhase(String viewId, FacesContext facesContext) throws FacesException {
    boolean skipFurtherProcessing = false;
    if (log.isTraceEnabled()) log.trace("entering applyRequestValues");

    informPhaseListenersBefore(facesContext, PhaseId.APPLY_REQUEST_VALUES);

    try {
      if (isResponseComplete(facesContext, "applyRequestValues", true)) {
        // have to return right away
        return true;
      }
      if (shouldRenderResponse(facesContext, "applyRequestValues", true)) {
        skipFurtherProcessing = true;
      }

      facesContext.getViewRoot().processDecodes(facesContext);
    } finally {
      informPhaseListenersAfter(facesContext, PhaseId.APPLY_REQUEST_VALUES);
    }

    if (isResponseComplete(facesContext, "applyRequestValues", false)
        || shouldRenderResponse(facesContext, "applyRequestValues", false)) {
      // since this phase is completed we don't need to return right away
      // even if the response is completed
      skipFurtherProcessing = true;
    }

    if (!skipFurtherProcessing && log.isTraceEnabled()) log.trace("exiting applyRequestValues");
    return skipFurtherProcessing;
  }
Example #30
0
 /**
  * finds the component with the given id that is located in the same NamingContainer as a given
  * component
  *
  * @param fc the FacesContext
  * @param componentId the component id
  * @param nearComponent a component within the same naming container from which to start the
  *     search (optional)
  * @return the component or null if no component was found
  */
 public UIComponent findComponent(FacesContext fc, String componentId, UIComponent nearComponent) {
   if (StringUtils.isEmpty(componentId))
     throw new InvalidArgumentException("componentId", componentId);
   // Begin search near given component (if any)
   UIComponent component = null;
   if (nearComponent != null) { // Search below the nearest naming container
     component = nearComponent.findComponent(componentId);
     if (component == null) { // Recurse upwards
       UIComponent nextParent = nearComponent;
       while (true) {
         nextParent = nextParent.getParent();
         // search NamingContainers only
         while (nextParent != null && !(nextParent instanceof NamingContainer)) {
           nextParent = nextParent.getParent();
         }
         if (nextParent == null) {
           break;
         } else {
           component = nextParent.findComponent(componentId);
         }
         if (component != null) {
           break;
         }
       }
     }
   }
   // Not found. Search the entire tree
   if (component == null) component = findChildComponent(fc.getViewRoot(), componentId);
   // done
   return component;
 }