예제 #1
1
  @Override
  public void validate(final FacesContext context) {
    context
        .getApplication()
        .publishEvent(context, PreValidateEvent.class, UIValidateForm.class, this);
    BeanManager manager = BeanManagerAccessor.getBeanManager();
    manager.fireEvent(this, BEFORE);

    Validator validator = context.getApplication().createValidator(validatorId);
    if (validator == null) {
      throw new IllegalArgumentException(
          "Could not create Validator with id: [" + validatorId + "]");
    }

    try {
      UIComponent parent = this.getParent();
      validator.validate(context, parent, components);
    } catch (ValidatorException e) {
      setValid(false);
      for (UIInput comp : components.values()) {
        comp.setValid(false);
        // TODO Put this back when attributes can control it
        // context.addMessage(comp.getClientId(), e.getFacesMessage());
      }
      context.addMessage(null, e.getFacesMessage());
    }

    manager.fireEvent(this, AFTER);
    context
        .getApplication()
        .publishEvent(context, PostValidateEvent.class, UIValidateForm.class, this);
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String token = request.getParameter("tk");
    String email = request.getParameter("email");

    if (token != null && !token.isEmpty() && email != null && !email.isEmpty()) {
      SolicitacaoRecuperacaoSenha solicitacaoRecuperacaoSenha =
          solicitacaoRecuperacaoSenhaBO.getSolicitacaoRecuperacaoSenha(token, email);
      if (solicitacaoRecuperacaoSenha != null) {
        // criar faces-context (no servlet o faces context nao existe e esse metodo forca sua
        // criacao)
        FacesContext context = FacesUtils.getFacesContext(request, response);
        Object object =
            context
                .getApplication()
                .evaluateExpressionGet(context, "#{sessaoUsuarioMB}", Object.class);
        if (object != null && object instanceof SessaoUsuarioMB) {
          SessaoUsuarioMB sessaoUsuarioMB = (SessaoUsuarioMB) object;
          sessaoUsuarioMB.setUser(null);
          sessaoUsuarioMB.setSolicitacaoRecuperacaoSenha(solicitacaoRecuperacaoSenha);
          response.sendRedirect(request.getContextPath() + "/cadastroNovaSenha.jsf");
          return;
        }
      }
    }

    response.sendRedirect(request.getContextPath());
  }
예제 #3
0
  public static void reportGlobalMessage(Severity severity, Exception ex) {
    FacesContext context = FacesContext.getCurrentInstance();
    context.validationFailed();
    String errMsg = null;

    if (ex instanceof UserEmailAddressException) {
      errMsg =
          context
              .getApplication()
              .getResourceBundle(context, "msg_communication")
              .getString("please-enter-a-valid-email-address");
    }
    if (ex instanceof MailboxUserSecretException) {
      errMsg =
          context
              .getApplication()
              .getResourceBundle(context, "msg_communication")
              .getString("please-enter-a-valid-user-secret");
    }
    if (ex instanceof SystemException) {
      if (ex.getMessage().equals("delete-requires-status-archived-or-inactive")) {
        errMsg =
            context
                .getApplication()
                .getResourceBundle(context, "msg_communication")
                .getString(ex.getMessage());
      }
    }

    if (errMsg == null) {
      errMsg = ex.getClass().getName();
    }
    context.addMessage(null, new FacesMessage(severity, errMsg, errMsg));
  }
예제 #4
0
  // TODO extract configured Mapping to FacesServlet
  @Override
  public String getRequestPath() {
    final FacesContext facesContext = FacesContext.getCurrentInstance();

    List<String> optionalParameters = new ArrayList<>(5);
    if (getLibraryName() != null) {
      optionalParameters.add("ln=" + getLibraryName());
    }
    if (!facesContext.isProjectStage(ProjectStage.Production)) {
      // append stage for all ProjectStages except Production
      optionalParameters.add("stage=" + facesContext.getApplication().getProjectStage().toString());
    }

    StringBuilder sb =
        new StringBuilder(30)
            .append(ResourceHandler.RESOURCE_IDENTIFIER)
            .append('/')
            .append(getResourceName())
            // the mapping has to be added, otherwise resources are not dispatched by the
            // FacesServlet
            .append(".xhtml");

    String parameterString = optionalParameters.stream().collect(Collectors.joining("&"));
    if (StringUtils.isNotBlank(parameterString)) {
      sb.append("?").append(parameterString);
    }

    return facesContext
        .getApplication()
        .getViewHandler()
        .getResourceURL(facesContext, sb.toString());
  }
예제 #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");
    }
  }
예제 #6
0
  /**
   * Translate the outcome attribute value to the target URL.
   *
   * @param context the current FacesContext
   * @param outcome the value of the outcome attribute
   * @return the target URL of the navigation rule (or the outcome if there's not navigation rule)
   */
  private String determineTargetURL(FacesContext context, String outcome) {
    ConfigurableNavigationHandler cnh =
        (ConfigurableNavigationHandler) context.getApplication().getNavigationHandler();
    NavigationCase navCase = cnh.getNavigationCase(context, null, outcome);
    /*
     * Param Name: javax.faces.PROJECT_STAGE Default Value: The default value is ProjectStage#Production but IDE can set it differently
     * in web.xml Expected Values: Development, Production, SystemTest, UnitTest Since: 2.0
     *
     * If we cannot get an outcome we use an Alert to give a feedback to the Developer if this build is in the Development Stage
     */
    if (navCase == null) {
      if (FacesContext.getCurrentInstance()
          .getApplication()
          .getProjectStage()
          .equals(ProjectStage.Development)) {
        return "alert('WARNING! " + W_NONAVCASE_BUTTON + "');";
      } else {
        return "";
      }
    } // throw new FacesException("The outcome '"+outcome+"' cannot be resolved."); }
    String vId = navCase.getToViewId(context);

    Map<String, List<String>> params = getParams(navCase, this);
    String url;
    url =
        context
            .getApplication()
            .getViewHandler()
            .getBookmarkableURL(
                context, vId, params, isIncludeViewParams() || navCase.isIncludeViewParams());
    return url;
  }
예제 #7
0
  /**
   * This code is currently common to all {@link ViewHandlingStrategy} instances.
   *
   * @see ViewHandler#calculateLocale(javax.faces.context.FacesContext)
   */
  public Locale calculateLocale(FacesContext context) {

    Util.notNull("context", context);

    Locale result = null;
    // determine the locales that are acceptable to the client based on the
    // Accept-Language header and the find the best match among the
    // supported locales specified by the client.
    Iterator<Locale> locales = context.getExternalContext().getRequestLocales();
    while (locales.hasNext()) {
      Locale perf = locales.next();
      result = findMatch(context, perf);
      if (result != null) {
        break;
      }
    }
    // no match is found.
    if (result == null) {
      if (context.getApplication().getDefaultLocale() == null) {
        result = Locale.getDefault();
      } else {
        result = context.getApplication().getDefaultLocale();
      }
    }
    return result;
  }
예제 #8
0
  public UIComponent createComponent(FaceletContext ctx) {

    FacesContext context = ctx.getFacesContext();
    UIComponent cc;
    // we have to handle the binding here, as Application doesn't
    // expose a method to do so with Resource.
    if (binding != null) {
      ValueExpression ve = binding.getValueExpression(ctx, UIComponent.class);
      cc = (UIComponent) ve.getValue(ctx);
      if (cc != null && !UIComponent.isCompositeComponent(cc)) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
          LOGGER.log(Level.SEVERE, "jsf.compcomp.binding.eval.non.compcomp", binding.toString());
        }
        cc = null;
      }
      if (cc == null) {
        cc = context.getApplication().createComponent(context, ccResource);
        ve.setValue(ctx, cc);
      }
    } else {
      cc = context.getApplication().createComponent(context, ccResource);
    }
    setCompositeComponent(context, cc);

    return cc;
  }
  public void onEventSelect(SelectEvent selectEvent) {
    UserEventVisibility visibility; // one of: CREATOR, VIEWER, NO_VISIBILITY
    int eventID;
    selectedEvent = (ScheduleEvent) selectEvent.getObject();
    eventID = Integer.parseInt(selectedEvent.getData().toString());
    String username = sessionUtility.getLoggedUser();

    try {
      visibility = um.getVisibilityOverEvent(eventID);
      sessionUtility.setParameter(eventID);
      SYSO_Testing.syso("FilterEvent. Username " + username);
      SYSO_Testing.syso("FilterEvent. I'm logged, and I've to check the visibility");
      if (visibility == CREATOR) {
        FacesContext fc = FacesContext.getCurrentInstance();
        sessionUtility.setParameter(eventID);
        fc.getApplication().getNavigationHandler().handleNavigation(fc, null, creatorOutcome);
        return;
      } else {
        if (visibility == VIEWER && !ef.find(eventID).isPrivateEvent()) {
          FacesContext fc = FacesContext.getCurrentInstance();
          sessionUtility.setParameter(eventID);
          fc.getApplication().getNavigationHandler().handleNavigation(fc, null, viewerOutcome);
          return;
        }
      }
    } catch (NotFoundException ex) {
      FacesContext fc = FacesContext.getCurrentInstance();
      fc.getApplication().getNavigationHandler().handleNavigation(fc, null, errorOutcome);
    }

    return;
  }
예제 #10
0
  public static Converter getItemConverter(FacesContext facesContext, UIComponent component) {
    Converter converter = null;
    if (component instanceof ValueHolder) {
      // If the component has an attached Converter, use it.
      converter = ((ValueHolder) component).getConverter();
      if (converter != null) {
        return converter;
      }
    }
    // If not, look for a ValueExpression for value (if any). The ValueExpression must point to
    // something that is:
    ValueExpression ve = component.getValueExpression("value");
    if (ve != null) {
      Class<?> valueType = ve.getType(facesContext.getELContext());
      // An array of primitives (such as int[]). Look up the registered by-class Converter for this
      // primitive type.
      // An array of objects (such as Integer[] or String[]). Look up the registered by-class
      // Converter for the underlying element type.
      if (valueType != null && valueType.isArray()) {
        converter = facesContext.getApplication().createConverter(valueType);
      }
      // A java.util.Collection. Do not convert the values.
    }
    if (converter == null) {
      // Spec says "If for any reason a Converter cannot be found, assume the type to be a String
      // array." However
      // if we don't have an explicit converter, see if one is registered for the class of the
      // SelectItem values
      Iterator<SelectItem> selectItems = SelectUtils.getSelectItems(facesContext, component);
      converter = getSelectItemConverter(facesContext.getApplication(), selectItems);
    }

    return converter;
  }
  private void writeSimulatorResources(
      FacesContext facesContext, DeviceResource component, Theme theme) throws IOException {
    ResponseWriter writer = facesContext.getResponseWriter();

    Resource simulatorCss =
        facesContext
            .getApplication()
            .getResourceHandler()
            .createResource(CSS_SIMULATOR, CSS_LOCATION, "text/css");
    writer.startElement(HTML.LINK_ELEM, component);
    writer.writeAttribute(HTML.TYPE_ATTR, HTML.LINK_TYPE_TEXT_CSS, HTML.TYPE_ATTR);
    writer.writeAttribute(HTML.REL_ATTR, HTML.STYLE_REL_STYLESHEET, HTML.REL_ATTR);
    writer.writeURIAttribute(HTML.HREF_ATTR, simulatorCss.getRequestPath(), HTML.HREF_ATTR);
    writer.endElement(HTML.LINK_ELEM);

    Resource simulatorScript =
        facesContext
            .getApplication()
            .getResourceHandler()
            .createResource(SCRIPT_SIMULATOR, UTIL_RESOURCE);
    String src = simulatorScript.getRequestPath();
    writer.startElement("script", component);
    writer.writeAttribute("type", "text/javascript", null);
    writer.writeAttribute("src", src, null);
    writer.endElement("script");

    writer.startElement("script", null);
    writer.writeAttribute("type", "text/javascript", null);
    writer.writeText("console.log('Welcome to the Matrix');", null);
    writer.endElement("script");
  }
예제 #12
0
  /**
   * This method looks up the parent object given a parentObjectExpression (Universal EL expression)
   *
   * @param facesContext
   * @param parentObjectExpression
   * @return
   */
  @DependsOnJSF
  @SuppressWarnings("deprecation")
  protected Object lookupParentObject(FacesContext facesContext) {
    if (parentClassOfTheField == null) {
      if (parentObject != null) {
        return parentObject;
      }
      assert parentObjectExpression != null;
      try {
        parentObject =
            facesContext
                .getApplication()
                .evaluateExpressionGet(facesContext, parentObjectExpression, Object.class);
        // JSF 1.1
        if (parentObject == null) {
          parentObject =
              facesContext
                  .getApplication()
                  .createValueBinding(parentObjectExpression)
                  .getValue(facesContext);
        }
        // JSF 1.2
        if (parentObject == null) {
          parentObject =
              facesContext
                  .getApplication()
                  .getExpressionFactory()
                  .createValueExpression(
                      facesContext.getELContext(), parentObjectExpression, parentClassOfTheField)
                  .getValue(facesContext.getELContext());
        }
        if (parentObject == null) {
          parentObject =
              facesContext
                  .getApplication()
                  .getExpressionFactory()
                  .createValueExpression(
                      facesContext.getELContext(), parentObjectExpression, Object.class)
                  .getValue(facesContext.getELContext());
        }
      } catch (Exception ex) {
        // System.out.println("All attempted methods failed!");
        ex.printStackTrace();
        assert facesContext != null;
        parentObject =
            facesContext
                .getApplication()
                .createValueBinding(parentObjectExpression)
                .getValue(facesContext);
        // System.out.println("Method in catch block = " + (parentObject==null?"failed":"passed"));
        assert parentObject != null;
      }
    }

    if (parentObject != null) {
      this.parentClassOfTheField = parentObject.getClass();
    }
    return parentObject;
  }
  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);
  }
예제 #14
0
  public void changeTreeActionListener(ValueChangeEvent evt) {
    String nodeTypeToShow = DEFAULT_PROJECT_ID;

    this.projectId = (String) evt.getNewValue();
    // Put into the session the current project used.
    this.webSessionService.setAttribute(WebSessionService.PROJECT_ID, this.projectId);

    if (!this.projectId.equals(DEFAULT_PROJECT_ID)) {

      // Retrieve the entire project.
      this.project = this.projectService.getProject(this.projectId);

      nodeTypeToShow = WilosObjectNode.PROJECTNODE;

      // masquage de la exptable d'instanciation
      String projectId = (String) this.webSessionService.getAttribute(WebSessionService.PROJECT_ID);
      Project project = this.projectService.getProject(projectId);

      FacesContext context = FacesContext.getCurrentInstance();

      ProcessBean processBean =
          (ProcessBean)
              context
                  .getApplication()
                  .getVariableResolver()
                  .resolveVariable(context, "Woops2ProcessBean");

      ExpTableBean expTableBean =
          (ExpTableBean)
              context
                  .getApplication()
                  .getVariableResolver()
                  .resolveVariable(context, "ExpTableBean");

      if (project.getProcess() == null) {
        processBean.setSelectedProcessGuid("default");
        expTableBean.setSelectedProcessGuid("default");
        processBean.setIsVisibleExpTable(false);
        expTableBean.setIsInstanciedProject(false);
        expTableBean.getExpTableContent().clear();
      } else {
        processBean.setSelectedProcessGuid(project.getProcess().getGuid());
        expTableBean.setSelectedProcessGuid(project.getProcess().getGuid());
        processBean.setIsVisibleExpTable(true);
        expTableBean.setIsInstanciedProject(true);
      }
    }

    this.buildTreeModel();

    if (this.projectId.length() > 0) this.selectNodeToShow(this.projectId, nodeTypeToShow);
  }
예제 #15
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;
 }
 private void redirectClient(FacesContext context) {
   HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
   ConnexionManagedBean connexionManagedBean =
       context
           .getApplication()
           .evaluateExpressionGet(context, "#{connexionManagedBean}", ConnexionManagedBean.class);
   if (connexionManagedBean == null) {
     log.error("Could not obtain instance of sessionBean");
     return;
   }
   if (connexionManagedBean.getAuthentificationLevel() != CLIENT) {
     addError(context, "access.clientrequired");
     context.getApplication().getNavigationHandler().handleNavigation(context, null, "login");
   }
 }
예제 #17
0
  @Override
  public BeanInfo getComponentMetadata(FacesContext context, Resource ccResource) {
    // PENDING this implementation is terribly wasteful.
    // Must find a better way.
    CompositeComponentBeanInfo result;
    FaceletContext ctx =
        (FaceletContext) context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
    FaceletFactory factory =
        (FaceletFactory) RequestStateManager.get(context, RequestStateManager.FACELET_FACTORY);
    VariableMapper orig = ctx.getVariableMapper();
    UIComponent tmp = context.getApplication().createComponent("javax.faces.NamingContainer");
    UIPanel facetComponent =
        (UIPanel) context.getApplication().createComponent("javax.faces.Panel");
    facetComponent.setRendererType("javax.faces.Group");
    tmp.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, facetComponent);
    // We have to put the resource in here just so the classes that eventually
    // get called by facelets have access to it.
    tmp.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY, ccResource);

    Facelet f;

    try {
      f = factory.getFacelet(ccResource.getURL());
      VariableMapper wrapper =
          new VariableMapperWrapper(orig) {

            @Override
            public ValueExpression resolveVariable(String variable) {
              return super.resolveVariable(variable);
            }
          };
      ctx.setVariableMapper(wrapper);
      context.getAttributes().put(IS_BUILDING_METADATA, Boolean.TRUE);
      f.apply(context, facetComponent);
    } catch (Exception e) {
      if (e instanceof FacesException) {
        throw (FacesException) e;
      } else {
        throw new FacesException(e);
      }
    } finally {
      context.getAttributes().remove(IS_BUILDING_METADATA);
      ctx.setVariableMapper(orig);
    }
    result = (CompositeComponentBeanInfo) tmp.getAttributes().get(UIComponent.BEANINFO_KEY);

    return result;
  }
예제 #18
0
파일: AreaBean.java 프로젝트: yaoliweb/cws
  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;
    }
  }
예제 #19
0
 @Override
 public Object getValue(ELContext context) {
   ELContext nxcontext = getLocalContext(context);
   Object res = null;
   if (originalValueExpression != null) {
     res = originalValueExpression.getValue(nxcontext);
     if (res instanceof String) {
       String expression = (String) res;
       if (ComponentTagUtils.isValueReference(expression)) {
         FacesContext faces = FacesContext.getCurrentInstance();
         Application app = faces.getApplication();
         ExpressionFactory factory = app.getExpressionFactory();
         ValueExpression newExpr =
             factory.createValueExpression(nxcontext, expression, expectedType);
         try {
           res = newExpr.getValue(nxcontext);
         } catch (ELException err) {
           log.error("Error processing expression " + expression + ": " + err);
           res = null;
         }
       } else {
         res = expression;
       }
     }
   }
   return res;
 }
 private String relatedControllerOutcome() {
   String relatedControllerString = JsfUtil.getRequestParameter("jsfcrud.relatedController");
   String relatedControllerTypeString =
       JsfUtil.getRequestParameter("jsfcrud.relatedControllerType");
   if (relatedControllerString != null && relatedControllerTypeString != null) {
     FacesContext context = FacesContext.getCurrentInstance();
     Object relatedController =
         context
             .getApplication()
             .getELResolver()
             .getValue(context.getELContext(), null, relatedControllerString);
     try {
       Class<?> relatedControllerType = Class.forName(relatedControllerTypeString);
       Method detailSetupMethod = relatedControllerType.getMethod("detailSetup");
       return (String) detailSetupMethod.invoke(relatedController);
     } catch (ClassNotFoundException e) {
       throw new FacesException(e);
     } catch (NoSuchMethodException e) {
       throw new FacesException(e);
     } catch (IllegalAccessException e) {
       throw new FacesException(e);
     } catch (InvocationTargetException e) {
       throw new FacesException(e);
     }
   }
   return null;
 }
예제 #21
0
  /** @see javax.faces.context.ExceptionHandlerWrapper#handle() */
  @Override
  public void handle() throws FacesException {
    Iterator<ExceptionQueuedEvent> it = getUnhandledExceptionQueuedEvents().iterator();
    while (it.hasNext()) {
      ExceptionQueuedEvent event = it.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      FacesContext facesContext = FacesContext.getCurrentInstance();

      ResourceBundle bundle = facesContext.getApplication().getResourceBundle(facesContext, "msg");

      Throwable t = context.getException();

      String title = bundle.getString("error.unhandled.title");
      String message = bundle.getString("error.unhandled.message") + t;

      if (logger.isErrorEnabled()) {
        logger.error(title, t);
      }

      facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, title, message));

      it.remove();
    }

    getWrapped().handle();
  }
예제 #22
0
 public static TimeOffController getController() {
   FacesContext fc = FacesContext.getCurrentInstance();
   return (TimeOffController)
       fc.getApplication()
           .getELResolver()
           .getValue(fc.getELContext(), null, "timeOffController");
 }
  @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();
  }
예제 #24
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);
 }
예제 #25
0
파일: Util.java 프로젝트: fiorenzino/giava
 public static String getArrayValue(String name, Long id, FacesContext fc) {
   if (name.compareTo("Nazioni") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getNazioni()
             .get(id)
             .getNazione();
   } else if (name.compareTo("Province") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getProvince()
             .get(id)
             .getProvincia();
   } else if (name.compareTo("Comuni") == 0) {
     return (String)
         ((PropertiesHandler) JSFUtils.getManagedBean("propertiesHandler"))
             .getComuni()
             .get(id)
             .getComune();
   } else {
     ArrayList<Object> array =
         (ArrayList<Object>)
             fc.getApplication().getELResolver().getValue(fc.getELContext(), null, name);
     return (String) array.get(id.intValue());
   }
 }
예제 #26
0
  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);
  }
예제 #27
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 String login() {
    IUser storedUser = authenticator.checkCredential(username, password);
    String outcome;

    if (storedUser != null) {
      setLoggedIn(true);
      user = storedUser;
      loginEvent.fire(new LoginEvent(storedUser, requestedRole, requestedStoreId));
      LOG.info(String.format("Successful login: username %s.", getUserName()));
      outcome =
          isStoreRequired()
              ? NavigationElements.STORE_MAIN.getNavigationOutcome()
              : NavigationElements.ENTERPRISE_MAIN.getNavigationOutcome();
    } else {
      FacesContext context = FacesContext.getCurrentInstance();
      String message =
          context
              .getApplication()
              .evaluateExpressionGet(context, "#{strings['login.failed.text']}", String.class);
      context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
      outcome = NavigationElements.LOGIN.getNavigationOutcome();
      LOG.warn(String.format("Failed login: username %s.", getUserName()));
    }
    return outcome;
  }
예제 #29
0
파일: CarBean.java 프로젝트: kowsercse/jsf
  /**
   * For each entry in data, create component and cause it to be populated with values.
   *
   * @param context the <code>FacesContext</code> for the current request
   * @param data a ResourceBundle
   */
  private void initComponentsFromProperties(FacesContext context, ResourceBundle data) {

    // populate the map
    for (Enumeration<String> keys = data.getKeys(); keys.hasMoreElements(); ) {

      String key = keys.nextElement();
      if (key == null) {
        continue;
      }
      // skip secondary keys.
      if (key.contains("_")) {
        continue;
      }
      String value = data.getString(key);
      String componentType = data.getString(key + "_componentType");
      String valueType = data.getString(key + "_valueType");
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(
            "populating map for "
                + key
                + "\n"
                + "\n\tvalue: "
                + value
                + "\n\tcomponentType: "
                + componentType
                + "\n\tvalueType: "
                + valueType);
      }
      // create the component for this componentType
      UIComponent component = context.getApplication().createComponent(componentType);
      populateComponentWithValue(context, component, componentType, value, valueType);
      components.put(key, component);
    }
  }
예제 #30
0
파일: AreaBean.java 프로젝트: yaoliweb/cws
  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;
    }
  }