/** Metodo responsavel por interceptar os eventos e validar o acesso as paginas do sistema. */
  public void afterPhase(PhaseEvent event) {

    FacesContext context = event.getFacesContext();

    String viewId = context.getViewRoot().getViewId();

    LoginBean loginBean =
        context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);

    if (!viewId.equals("/logout.xhtml") && !viewId.equals("/login.xhtml")) {

      loginBean.autenticar();

      if (loginBean.getUsuarioAutenticado() != null) {
        ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest();
        this.remoteAddress = request.getRemoteAddr();
        logger.warning("Acesso permitido em " + viewId + " por " + this.remoteAddress);

      } else {
        ExternalContext externalContext = context.getExternalContext();
        HttpSession httpSession = (HttpSession) externalContext.getSession(false);
        httpSession.invalidate();

        ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest();

        this.remoteAddress = request.getRemoteAddr();

        if (loginBean.getUsuarioAutenticado() == null) {
          logger.warning("Acesso indevido em " + viewId + " por " + this.remoteAddress + ".");
        }
      }
    }
  }
  @Override
  public BrowserSniffer getBrowserSniffer(ExternalContext externalContext) {

    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();

    return new BrowserSnifferImpl(httpServletRequest);
  }
  public static Object resolveBean(String beanName, TabScopeManager context) {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    if (externalContext instanceof ServletExternalContext) {
      HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

      // save backup of current binding to cope with nested tags?
      Object contextBackup = request.getAttribute(PARAM_CURRENT_MANAGER);
      request.setAttribute(PARAM_CURRENT_MANAGER, context);
      try {
        return FacesUtils.getBeanFromContext(fc, beanName);
      } finally {
        if (null != contextBackup) {
          request.setAttribute(PARAM_CURRENT_MANAGER, contextBackup);
        } else {
          request.removeAttribute(PARAM_CURRENT_MANAGER);
        }
      }
    } else if (externalContext instanceof PortletExternalContext) {
      // TODO portlets
      trace.warn("Portlets are not yet supported.");
    }

    return null;
  }
Beispiel #4
0
 /**
  * Downloads a blob and sends it to the requesting user, in the JSF current context.
  *
  * @param doc the document, if available
  * @param xpath the blob's xpath or blobholder index, if available
  * @param blob the blob, if already fetched
  * @param filename the filename to use
  * @param reason the download reason
  * @param extendedInfos an optional map of extended informations to log
  * @since 7.3
  */
 public static void download(
     DocumentModel doc,
     String xpath,
     Blob blob,
     String filename,
     String reason,
     Map<String, Serializable> extendedInfos) {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   if (facesContext.getResponseComplete()) {
     // nothing can be written, an error was probably already sent. don't bother
     log.debug("Cannot send " + filename + ", response already complete");
     return;
   }
   if (facesContext.getPartialViewContext().isAjaxRequest()) {
     // do not perform download in an ajax request
     return;
   }
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
   HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
   try {
     DownloadService downloadService = Framework.getService(DownloadService.class);
     downloadService.downloadBlob(
         request, response, doc, xpath, blob, filename, reason, extendedInfos);
   } catch (IOException e) {
     log.error("Error while downloading the file: " + filename, e);
   } finally {
     facesContext.responseComplete();
   }
 }
  /**
   * Resets/restores the values in the portletPreferences.xhtml Facelet composition with portlet
   * preference default values.
   */
  public void reset() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();

    try {
      Enumeration<String> preferenceNames = portletPreferences.getNames();

      while (preferenceNames.hasMoreElements()) {
        String preferenceName = preferenceNames.nextElement();
        portletPreferences.reset(preferenceName);
      }

      portletPreferences.store();

      // Switch the portlet mode back to VIEW.
      ActionResponse actionResponse = (ActionResponse) externalContext.getResponse();
      actionResponse.setPortletMode(PortletMode.VIEW);
      actionResponse.setWindowState(WindowState.NORMAL);

      FacesContextHelperUtil.addGlobalSuccessInfoMessage();
    } catch (Exception e) {
      FacesContextHelperUtil.addGlobalUnexpectedErrorMessage();
    }
  }
Beispiel #6
0
  /**
   * Perform actions that need to happen on the <code>afterPhase</code> event.
   *
   * <p>For after restore-view, if this is a postback, we extract the sequenceId from the request
   * and store it in the request scope.
   *
   * <p>For after render-response, we clear out the flash for the postback, while leaving the
   * current one intact.
   */
  public void afterPhase(PhaseEvent e) {
    FacesContext context = e.getFacesContext();
    ExternalContext extContext = context.getExternalContext();
    Map<String, Object> requestMap = extContext.getRequestMap();
    Object request = extContext.getRequest(), response = extContext.getResponse();
    ELFlash elFlash = ELFlash.getELFlash();

    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      expireEntries(context);
    }

    // If this requset is ending normally...
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        elFlash.saveAllMessages(context);
      }
    }
    // Otherwise, if this request is ending early...
    else if ((context.getResponseComplete() || context.getRenderResponse())
        && elFlash.isRedirect()) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        addCookie(extContext, elFlash);
        elFlash.saveAllMessages(context);
      }
    }
  }
 private HttpServletRequest getRequest() {
   HttpServletRequest request = null;
   ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
   if (context != null) {
     request = (HttpServletRequest) context.getRequest();
   }
   return request;
 }
Beispiel #8
0
 /** @return the renderRequest */
 public RenderRequest getRenderRequest() {
   if (renderRequest == null) {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     ExternalContext extContext = facesContext.getExternalContext();
     renderRequest = (RenderRequest) extContext.getRequest();
   }
   return renderRequest;
 }
Beispiel #9
0
  private EntityManager getEntityManager() {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) ec.getRequest();
    EntityManager manager = (EntityManager) request.getAttribute("EntityManager");

    return manager;
  }
Beispiel #10
0
 /**
  * Retorna el nombre del proyecto de la aplicación web
  *
  * @return
  */
 public String getNombreProyecto() {
   ExternalContext iecx = FacesContext.getCurrentInstance().getExternalContext();
   HttpServletRequest request = (HttpServletRequest) iecx.getRequest();
   String contexto = request.getContextPath() + "";
   contexto = contexto.replace("/", "");
   contexto = contexto.trim();
   return contexto;
 }
 /** @return true if an exception have been detected. */
 public boolean isException() {
   if (isPortletMode()) {
     FacesContext facesContext = FacesContext.getCurrentInstance();
     ExternalContext externalContext = facesContext.getExternalContext();
     PortletRequest request = (PortletRequest) externalContext.getRequest();
     ContextUtils.bindRequestAndContext(request, (PortletContext) externalContext.getContext());
   }
   return ExceptionUtils.getMarkedExceptionService() != null;
 }
 public void changeOperator() {
   FacesContext facesContext = FacesContext.getCurrentInstance();
   ExternalContext externalContext = facesContext.getExternalContext();
   String requestURI = ((HttpServletRequest) externalContext.getRequest()).getRequestURI();
   try {
     externalContext.redirect(requestURI);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * Saves the values in the portletPreferences.xhtml Facelet composition as portlet preferences.
   */
  public void submit() {

    // The JSR 329 specification defines an EL variable named mutablePortletPreferencesValues that
    // is being used in
    // the portletPreferences.xhtml Facelet composition. This object is of type Map<String,
    // Preference> and is
    // designed to be a model managed-bean (in a sense) that contain preference values. However the
    // only way to
    // access this from a Java class is to evaluate an EL expression (effectively self-injecting)
    // the map into
    // this backing bean.
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    String elExpression = "mutablePortletPreferencesValues";
    ELResolver elResolver = facesContext.getApplication().getELResolver();
    @SuppressWarnings("unchecked")
    Map<String, Preference> mutablePreferenceMap =
        (Map<String, Preference>)
            elResolver.getValue(facesContext.getELContext(), null, elExpression);

    // Get a list of portlet preference names.
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletPreferences portletPreferences = portletRequest.getPreferences();
    Enumeration<String> preferenceNames = portletPreferences.getNames();

    try {

      // For each portlet preference name:
      while (preferenceNames.hasMoreElements()) {

        // Get the value specified by the user.
        String preferenceName = preferenceNames.nextElement();
        String preferenceValue = mutablePreferenceMap.get(preferenceName).getValue();

        // Prepare to save the value.
        if (!portletPreferences.isReadOnly(preferenceName)) {
          portletPreferences.setValue(preferenceName, preferenceValue);
        }
      }

      // Save the preference values.
      portletPreferences.store();

      // Switch the portlet mode back to VIEW.
      ActionResponse actionResponse = (ActionResponse) externalContext.getResponse();
      actionResponse.setPortletMode(PortletMode.VIEW);
      actionResponse.setWindowState(WindowState.NORMAL);

      // Report a successful message back to the user as feedback.
      FacesContextHelperUtil.addGlobalSuccessInfoMessage();
    } catch (Exception e) {
      FacesContextHelperUtil.addGlobalUnexpectedErrorMessage();
    }
  }
  public void login() {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

    try {
      if (StringUtils.isBlank(request.getRemoteUser())) {
        // request.logout();
        request.login(this.username, this.password);

      } else if (!request.getRemoteUser().equals(this.username)) {
        request.logout();
        request.login(this.username, this.password);
      }

      if (originalURL != null && originalURL.indexOf("service.jsf?") > 0) {
        externalContext.redirect(originalURL);
      } else {

        if (UserDAO.isProvider(this.username)) {
          String recentServiceId = serviceDAO.getProviderRecentServiceId(this.username);
          if (recentServiceId == null)
            externalContext.redirect(
                externalContext.getRequestContextPath() + "/provider/providerappointment.jsf");
          else
            externalContext.redirect(
                externalContext.getRequestContextPath()
                    + "/provider/serviceappointment.jsf?serviceId="
                    + recentServiceId);
        } else {
          String recentServiceId = serviceDAO.getUserRecentServiceId(this.username);
          if (recentServiceId == null)
            externalContext.redirect(
                externalContext.getRequestContextPath() + "/user/userappointment.jsf");
          else
            externalContext.redirect(
                externalContext.getRequestContextPath()
                    + "/user/appointment.jsf?serviceId="
                    + recentServiceId);
        }
      }
    } catch (Exception e) {
      // log.error(e.getCause(), e);
      WebUtil.addMessage(
          new FacesMessage(
              FacesMessage.SEVERITY_INFO,
              WebUtil.getMessage("login.failed.header"),
              WebUtil.getMessage("login.failed.message")));

      // context.addMessage(null, new FacesMessage("Login failed."));
    }
  }
 public static String getBaseUrl() {
   ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
   HttpServletRequest request = (HttpServletRequest) context.getRequest();
   StringBuilder baseUrl = new StringBuilder();
   baseUrl
       .append(request.getScheme())
       .append("://")
       .append(request.getServerName())
       .append(":")
       .append(request.getServerPort())
       .append(request.getContextPath());
   return baseUrl.toString();
 }
  public JobBoardPageController() {
    template = "JobBoardTemplate.xhtml";
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Object request = externalContext.getRequest();
    if (request instanceof HttpServletRequest) {
      HttpServletRequest httpServletRequest = (HttpServletRequest) request;

      if (httpServletRequest.getHeader("User-Agent").indexOf("Mobile") != -1) {
        template = "JobBoardTemplateMobile.xhtml";
      } else {
        template = "JobBoardTemplate.xhtml";
      }
    }
  }
 protected void handleException(FacesContext context, Exception e) {
   try {
     ExternalContext externalContext = context.getExternalContext();
     ExceptionHandlingService exceptionHandlingService =
         Framework.getService(ExceptionHandlingService.class);
     NuxeoExceptionHandler handler = exceptionHandlingService.getExceptionHandler();
     handler.handleException(
         (HttpServletRequest) externalContext.getRequest(),
         (HttpServletResponse) externalContext.getResponse(),
         e);
   } catch (ServletException | IOException e1) {
     throw new NuxeoException(e1);
   }
 }
  public static void bindTabScope(TabScopeManager tabScopeManager) {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    if (externalContext instanceof ServletExternalContext) {
      HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

      // TODO save backup of current binding to cope with nested tags?

      request.setAttribute(PARAM_CURRENT_MANAGER, tabScopeManager);
    } else if (externalContext instanceof PortletExternalContext) {
      // TODO portlets
      trace.warn("Portlets are not yet supported.");
    }
  }
 @Override
 public void afterPhase(PhaseEvent event) {
   FacesContext facesContext = event.getFacesContext();
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
   if (!request.getMethod().equals("POST")) {
     Map<?, ?> flashScope =
         (Map<?, ?>)
             facesContext
                 .getApplication()
                 .createValueBinding("#{flashScope}")
                 .getValue(facesContext);
     flashScope.clear();
   }
 }
  public static void unbindTabScope(TabScopeManager tabScopeManager) {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    if (externalContext instanceof ServletExternalContext) {
      HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
      Object currentlyBoundManager = request.getAttribute(PARAM_CURRENT_MANAGER);
      if (currentlyBoundManager == tabScopeManager) {
        request.removeAttribute(PARAM_CURRENT_MANAGER);
      }

      // TODO restore backup of previous binding to cope with nested tags?
    } else if (externalContext instanceof PortletExternalContext) {
      // TODO portlets
      trace.warn("Portlets are not yet supported.");
    }
  }
Beispiel #21
0
  public void onPageLoad() {
    initUserContext();
    if (!checkUserAccess(userContext.getUserCode(), this.getClass().getName())) {
      FacesContext fctx = FacesContext.getCurrentInstance();
      ExternalContext ectx = fctx.getExternalContext();
      String url =
          ((HttpServletRequest) ectx.getRequest()).getContextPath()
              + "/pages/common/restrictionAccess.jsf";
      try {
        ectx.redirect(url);
      } catch (IOException e) {

        e.printStackTrace();
      }
    }
    ;
  }
  @Before
  public void setup() {
    gotoBean = spy(new GotoMarketplaceBean());

    FacesContext fcContextMock = mock(FacesContext.class);
    when(gotoBean.getFacesContext()).thenReturn(fcContextMock);

    // mock the ExternalContext's getRequest() method
    ExternalContext externalContextMock = mock(ExternalContext.class);
    when(fcContextMock.getExternalContext()).thenReturn(externalContextMock);

    HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class);
    when(externalContextMock.getRequest()).thenReturn(httpServletRequestMock);

    // mock the HttpServletRequest's getSession() method
    sessionMock = mock(HttpSession.class);
    when(httpServletRequestMock.getSession()).thenReturn(sessionMock);
  }
  public ListaOrdenesCompra() {

    Principal userPrincipal =
        FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
    if (userPrincipal == null) {
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              new FacesMessage(
                  FacesMessage.SEVERITY_ERROR, "Error", "Error al obtener el nombre del usuario"));
      System.err.println("Error obteniendo el 'principal' del usuario.");
      return;
    }

    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    Object request = ec.getRequest();
    String usuario = ((PortletRequest) request).getUserPrincipal().getName();

    servProxy = ServicioProxy.getInstance();
    nit = servProxy.getNitByUsername(usuario);

    // boolean
    // bcomercio=FacesContext.getCurrentInstance().getExternalContext().isUserInRole("Comercio");
    // boolean
    // bfabricante=FacesContext.getCurrentInstance().getExternalContext().isUserInRole("Fabricante");
    String rol = "";
    try {
      rol = LDAPAuthenticationManagementPortClient.getInstanceLDapRol().obtenerRol(nit);
    } catch (UsuarioNoExisteException e) {
      // TODO
      return;
    }
    // String rol = "Fabricante";//UsuariosUtils.getInstance().obtenerRolUsuario(usuario);
    if (rol.equals(TipoClienteConstants.COMERCIO)) {
      comercio = true;
      ordenes = servProxy.getOrdenCompraByNitComercio(nit);
    }
    if (rol.equals(TipoClienteConstants.FABRICANTE)) {
      ordenes = servProxy.getOrdenCompraByNitFabricante(nit);
    }
  }
  @Override
  public void decode(FacesContext context, UIComponent component) {

    rendererParamsNotNull(context, component);

    if (!shouldDecode(component)) {
      return;
    }

    String clientId = decodeBehaviors(context, component);

    if (clientId == null) {
      clientId = component.getClientId(context);
    }

    assert (clientId != null);
    ExternalContext externalContext = context.getExternalContext();
    Map<String, String> requestMap = externalContext.getRequestParameterMap();

    if (requestMap.containsKey(clientId)) {
      setSubmittedValue(component, requestMap.get(clientId));
    }

    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    try {
      Collection<Part> parts = request.getParts();
      List<Part> multiple = new ArrayList<>();
      for (Part cur : parts) {
        if (clientId.equals(cur.getName())) {
          component.setTransient(true);
          multiple.add(cur);
        }
      }
      this.setSubmittedValue(component, multiple);
    } catch (IOException | ServletException ioe) {
      throw new FacesException(ioe);
    }
  }
Beispiel #25
0
  public void login() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

    try {
      System.out.println("Logging in");
      System.out.println("UN=" + username);
      System.out.println("PW=" + password);
      //            request.login(username, appUserService.encodePassword(password));
      request.login(username, password);
      //            User user = userService.find(username, password);
      //            externalContext.getSessionMap().put("user", user);
      refreshUserSessionBean(username);
      externalContext.redirect(originalURL);
    } catch (ServletException e) {
      // Handle unknown username/password in request.login().
      LOGGER.error(e);
      context.addMessage(
          null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unknown login", null));
      System.out.println("Unknown login");
    }
  }
Beispiel #26
0
 public String getURLCompleto() {
   ExternalContext iecx = FacesContext.getCurrentInstance().getExternalContext();
   HttpServletRequest request = (HttpServletRequest) iecx.getRequest();
   String path = request.getRequestURL() + "";
   return path;
 }
Beispiel #27
0
  // <editor-fold defaultstate="collapsed" desc="Funciones varias" >
  public void reload() throws IOException {
    // ...

    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
  }
  @Override
  public Object getValue(ELContext context, Object base, Object property) throws ELException {
    // variable resolution is a special case of property resolution
    // where the base is null.
    if (!BridgeUtil.isPortletRequest() || base != null) {
      return null;
    }
    if (property == null) {
      throw new PropertyNotFoundException("Null property");
    }

    FacesContext facesContext = (FacesContext) context.getContext(FacesContext.class);
    ExternalContext extCtx = facesContext.getExternalContext();

    // only process if running in a portlet request
    // Bridge.PortletPhase phase =
    // (Bridge.PortletPhase)
    // FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get(Bridge.PORTLET_LIFECYCLE_PHASE);
    // if (phase == null) {
    // return null;
    // }

    if (PORTLET_CONFIG.equals(property)) {
      context.setPropertyResolved(true);
      return context.getContext(PortletConfig.class);
    } else if (ACTION_REQUEST.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.ACTION_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getRequest();
    } else if (ACTION_RESPONSE.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.ACTION_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getResponse();
    } else if (RENDER_REQUEST.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.RENDER_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getRequest();
    } else if (RENDER_RESPONSE.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.RENDER_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getResponse();
    } else if (EVENT_REQUEST.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.EVENT_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getRequest();
    } else if (EVENT_RESPONSE.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.EVENT_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getResponse();
    } else if (RESOURCE_REQUEST.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.RESOURCE_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getRequest();
    } else if (RESOURCE_RESPONSE.equals(property)
        && (BridgeUtil.getPortletRequestPhase() == Bridge.PortletPhase.RESOURCE_PHASE)) {
      context.setPropertyResolved(true);
      return extCtx.getResponse();
    } else if (SESSION_APPLICATION_SCOPE.equals(property) || HTTP_SESSION_SCOPE.equals(property)) {
      context.setPropertyResolved(true);
      if (mAppScopeSessionMap == null) {
        Object request = extCtx.getRequest();
        // Object portletLifecycleAttr = extCtx.getRequestMap().get(Bridge.PORTLET_LIFECYCLE_PHASE);
        if (BridgeUtil.isPortletRequest()) {
          mAppScopeSessionMap = new PortletApplicationScopeSessionMap((PortletRequest) request);
        }
      }
      return mAppScopeSessionMap;
    } else if (SESSION_PORTLET_SCOPE.equals(property) || PORTLET_SESSION_SCOPE.equals(property)) {
      context.setPropertyResolved(true);
      return extCtx.getSessionMap();
    } else if (PORTLET_SESSION.equals(property)) {
      context.setPropertyResolved(true);
      return extCtx.getSession(false);
    } else if (PORTLET_PREFERENCE_VALUE.equals(property)) {
      context.setPropertyResolved(true);
      return getPreferencesValueMap(facesContext);
    } else if (PORTLET_PREFERENCES.equals(property)) {
      context.setPropertyResolved(true);
      return ((PortletRequest) extCtx.getRequest()).getPreferences();
    } else if (MUTABLE_PORTLET_PREFERENCES_VALUES.equals(property)) {
      context.setPropertyResolved(true);
      return getPreferenceMap(((PortletRequest) extCtx.getRequest()).getPreferences());
    } else {
      return null;
    }
    // }
  }
  @Override
  public void encodeBegin(FacesContext facesContext, UIComponent uiComponent) throws IOException {

    super.encodeBegin(facesContext, uiComponent);

    InputEditorInternal inputEditorInternal = (InputEditorInternal) uiComponent;
    ResponseWriter responseWriter = facesContext.getResponseWriter();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(portletRequest);
    httpServletRequest = new NonNamespacedHttpServletRequest(httpServletRequest);

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(portletResponse);
    PortletRequest liferayPortletRequest = getLiferayPortletRequest(portletRequest);
    boolean resourcePhase = (liferayPortletRequest instanceof ResourceRequest);
    Map<String, Object> attributes = inputEditorInternal.getAttributes();
    String onBlurMethod = (String) attributes.get("onBlurMethod");
    String editorImpl = (String) attributes.get("editorImpl");

    if (editorImpl == null) {
      editorImpl = CKEDITOR;
    }

    // Build up a URL that can be used to invoke the liferay-ui:input-editor JSP tag.
    String url = "/resources/liferay-ui/jsp/input-editor.jsp";
    StringBuilder queryString = new StringBuilder();
    queryString.append(StringPool.QUESTION);
    queryString.append("editorImpl");
    queryString.append(StringPool.EQUAL);
    queryString.append(editorImpl);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("height");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("height"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("initMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("initMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("name");
    queryString.append(StringPool.EQUAL);

    String editorName = (String) attributes.get("name");
    queryString.append(editorName);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("onChangeMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("onChangeMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("skipEditorLoading");
    queryString.append(StringPool.EQUAL);

    if (resourcePhase) {

      // FACES-1439: Ensure that the <script src=".../ckeditor.js" /> element is not included in the
      // response by
      // specifying skipEditorLoading="true" during Ajax requests.
      queryString.append(Boolean.TRUE.toString());
    } else {
      queryString.append(Boolean.FALSE.toString());
    }

    queryString.append(StringPool.AMPERSAND);
    queryString.append("toolbarSet");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("toolbarSet"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("width");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("width"));
    url = url + queryString.toString();

    // Invoke the tag and capture it's output in a String, rather than having the output go directly
    // to the
    // response.
    RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher(url);
    JspIncludeResponse jspIncludeResponse = new JspIncludeResponse(httpServletResponse);

    try {
      requestDispatcher.include(httpServletRequest, jspIncludeResponse);
    } catch (ServletException e) {
      logger.error(e.getMessage());
      throw new IOException(e.getMessage());
    }

    String bufferedResponse = jspIncludeResponse.getBufferedResponse();

    if (bufferedResponse != null) {

      // Note: Trim the buffered response since there is typically over 100 newlines at the
      // beginning.
      bufferedResponse = bufferedResponse.trim();

      // If rendering an instance of the CKEditor, then
      String editorType = EditorUtil.getEditorValue(httpServletRequest, editorImpl);

      if (editorType.indexOf(CKEDITOR) >= 0) {

        String namespace = portletResponse.getNamespace();

        // FACES-1441: The liferay-ui:input-editor JSP tag (and associated ckeditor.jsp file) do not
        // provide a
        // way to hook-in to the "onblur" callback feature of the CKEditor. In order to overcome
        // this
        // limitation, it is necessary to append a <script>...</script> to the response that
        // provides this
        // ability.
        String onBlurScript = getOnBlurScript(editorName, onBlurMethod, namespace);

        // If running within an Ajax request, include the "onblur" callback script must be included
        // directly
        // to the response.
        if (resourcePhase) {

          StringBuilder scriptMarkup = new StringBuilder();
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          scriptMarkup.append(StringPool.CDATA_OPEN);
          scriptMarkup.append(onBlurScript);
          scriptMarkup.append(COMMENT_CDATA_CLOSE);
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.FORWARD_SLASH);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          bufferedResponse = bufferedResponse.concat(scriptMarkup.toString());
        }

        // Otherwise, append the script to the "LIFERAY_SHARED_AUI_SCRIPT_DATA" request attribute,
        // which will
        // cause the script to be rendered at the bottom of the portal page.
        else {

          ScriptData scriptData =
              (ScriptData) externalContext.getRequestMap().get(WebKeys.AUI_SCRIPT_DATA);
          scriptData.append(getPortletId(portletRequest), onBlurScript, null);
        }

        // FACES-1439: If the component was rendered on the page on the previous JSF lifecycle, then
        // prevent it
        // from being re-initialized by removing all <script>...</script> elements.
        boolean scriptsRemoved = false;

        String clientId = inputEditorInternal.getClientId();

        if (resourcePhase && inputEditorInternal.isPreviouslyRendered()) {

          logger.debug("Preventing re-initialization of CKEditor for clientId=[{0}]", clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();
          scriptsRemoved = true;
        }

        // FACES-1422: Move the scripts to the <eval>...</eval> section of the partial-response so
        // that they
        // will execute properly. This has the added benefit of preempt a DOM-diff with ICEfaces.
        if (resourcePhase && !scriptsRemoved) {

          logger.debug(
              "Moving CKEditor scripts to <eval>...</eval> section of the partial-response for clientId=[{0}]",
              clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();

          String scripts = parsedResponse.getScripts();

          LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
          liferayFacesContext.getJavaScriptMap().put(clientId, scripts);
          logger.trace(scripts);
        }
      }

      // Write the captured output from the JSP tag to the Faces responseWriter.
      logger.trace(bufferedResponse);
      responseWriter.write(bufferedResponse);
    }
  }
Beispiel #30
0
  /**
   * Execute the target view. If the HTTP status code range is not 2xx, then return true to indicate
   * the response should be immediately flushed by the caller so that conditions such as 404 are
   * properly handled.
   *
   * @param context the <code>FacesContext</code> for the current request
   * @param viewToExecute the view to build
   * @return <code>true</code> if the response should be immediately flushed to the client,
   *     otherwise <code>false</code>
   * @throws java.io.IOException if an error occurs executing the page
   */
  private boolean executePageToBuildView(FacesContext context, UIViewRoot viewToExecute)
      throws IOException {

    if (null == context) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }
    if (null == viewToExecute) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "viewToExecute");
      throw new NullPointerException(message);
    }

    ExternalContext extContext = context.getExternalContext();

    if ("/*".equals(RequestStateManager.get(context, RequestStateManager.INVOCATION_PATH))) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.FACES_SERVLET_MAPPING_INCORRECT_ID));
    }

    String requestURI = viewToExecute.getViewId();

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("About to execute view " + requestURI);
    }

    // update the JSTL locale attribute in request scope so that JSTL
    // picks up the locale from viewRoot. This attribute must be updated
    // before the JSTL setBundle tag is called because that is when the
    // new LocalizationContext object is created based on the locale.
    if (extContext.getRequest() instanceof ServletRequest) {
      Config.set(
          (ServletRequest) extContext.getRequest(),
          Config.FMT_LOCALE,
          context.getViewRoot().getLocale());
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Before dispacthMessage to viewId " + requestURI);
    }

    // save the original response
    Object originalResponse = extContext.getResponse();

    // replace the response with our wrapper
    ViewHandlerResponseWrapper wrapped = getWrapper(extContext);
    extContext.setResponse(wrapped);

    try {

      // build the view by executing the page
      extContext.dispatch(requestURI);

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("After dispacthMessage to viewId " + requestURI);
      }
    } finally {
      // replace the original response
      extContext.setResponse(originalResponse);
    }

    // Follow the JSTL 1.2 spec, section 7.4,
    // on handling status codes on a forward
    if (wrapped.getStatus() < 200 || wrapped.getStatus() > 299) {
      // flush the contents of the wrapper to the response
      // this is necessary as the user may be using a custom
      // error page - this content should be propagated
      wrapped.flushContentToWrappedResponse();
      return true;
    }

    // Put the AFTER_VIEW_CONTENT into request scope
    // temporarily
    RequestStateManager.set(context, RequestStateManager.AFTER_VIEW_CONTENT, wrapped);

    return false;
  }