예제 #1
0
  /** Ssets the locale context-wide based on a call to {@link JiveGlobals#getLocale()}. */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    final String pathInfo = ((HttpServletRequest) request).getPathInfo();

    if (pathInfo == null) {
      // Note, putting the locale in the application at this point is a little overkill
      // (ie, every user who hits this filter will do this). Eventually, it might make
      // sense to just set the locale in the user's session and if that's done we might
      // want to honor a preference to get the user's locale based on request headers.
      // For now, this is just a convenient place to set the locale globally.
      Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale());
    } else {
      try {
        String[] parts = pathInfo.split("/");
        String pluginName = parts[1];
        ResourceBundle bundle = LocaleUtils.getPluginResourceBundle(pluginName);
        LocalizationContext ctx = new LocalizationContext(bundle, JiveGlobals.getLocale());
        Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, ctx);
      } catch (Exception e) {
        // Note, putting the locale in the application at this point is a little overkill
        // (ie, every user who hits this filter will do this). Eventually, it might make
        // sense to just set the locale in the user's session and if that's done we might
        // want to honor a preference to get the user's locale based on request headers.
        // For now, this is just a convenient place to set the locale globally.
        Config.set(context, Config.FMT_LOCALE, JiveGlobals.getLocale());
      }
    }
    // Move along:
    chain.doFilter(request, response);
  }
예제 #2
0
  @Override
  @Produces
  public ResourceBundle getBundle(Locale locale) {
    Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, null);
    ResourceBundle customBundle = super.getBundle(locale);
    Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, "mamute-messages");
    ResourceBundle mamuteBundle = super.getBundle(locale);

    return new MamuteResourceBundle(customBundle, mamuteBundle);
  }
  @Override
  public Locale resolveLocale(HttpServletRequest request) {

    Object locale = Config.get(request, Config.FMT_LOCALE);
    if (locale == null) {
      HttpSession session = request.getSession(false);
      if (session != null) {
        locale = Config.get(session, Config.FMT_LOCALE);
      }
    }

    return (locale instanceof Locale ? (Locale) locale : null);
  }
예제 #4
0
 public static Locale getJstlLocale(HttpServletRequest request, ServletContext servletContext) {
   Object localeObject = Config.get(request, Config.FMT_LOCALE);
   if (localeObject == null) {
     HttpSession session = request.getSession(false);
     if (session != null) {
       localeObject = Config.get(session, Config.FMT_LOCALE);
     }
     if (localeObject == null && servletContext != null) {
       localeObject = Config.get(servletContext, Config.FMT_LOCALE);
     }
   }
   return (localeObject instanceof Locale ? (Locale) localeObject : null);
 }
예제 #5
0
 public static TimeZone getJstlTimeZone(
     HttpServletRequest request, ServletContext servletContext) {
   Object timeZoneObject = Config.get(request, Config.FMT_TIME_ZONE);
   if (timeZoneObject == null) {
     HttpSession session = request.getSession(false);
     if (session != null) {
       timeZoneObject = Config.get(session, Config.FMT_TIME_ZONE);
     }
     if (timeZoneObject == null && servletContext != null) {
       timeZoneObject = Config.get(servletContext, Config.FMT_TIME_ZONE);
     }
   }
   return (timeZoneObject instanceof TimeZone ? (TimeZone) timeZoneObject : null);
 }
예제 #6
0
  /**
   * Get the Locale for a session according to the user's language selection or language
   * preferences. Order of selection - language selected via UI - language as set by application -
   * language browser default
   *
   * @param request the request Object
   * @return supportedLocale Locale supported by this DSpace Instance for this request
   */
  public static Locale getSessionLocale(HttpServletRequest request) {

    String paramLocale = request.getParameter("locale");
    Locale sessionLocale = null;
    Locale supportedLocale = null;

    if (!StringUtils.isEmpty(paramLocale)) {
      /* get session locale according to user selection */
      sessionLocale = new Locale(paramLocale);
    }

    if (sessionLocale == null) {
      /* get session locale set by application */
      HttpSession session = request.getSession();
      sessionLocale = (Locale) Config.get(session, Config.FMT_LOCALE);
    }

    /*
     * if session not set by selection or application then default browser
     * locale
     */
    if (sessionLocale == null) {
      sessionLocale = request.getLocale();
    }

    if (sessionLocale == null) {
      sessionLocale = I18nUtil.DEFAULTLOCALE;
    }
    supportedLocale = I18nUtil.getSupportedLocale(sessionLocale);

    return supportedLocale;
  }
예제 #7
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
    ServletRequest servletRequest = request;
    try {
      if (request instanceof HttpServletRequest) {
        Cookie[] cookies = ((HttpServletRequest) request).getCookies();
        String localeCode = "";
        if (cookies != null) {
          for (Cookie cookie : cookies) {
            if ("pyramusLocale".equals(cookie.getName())) {
              localeCode = cookie.getValue();
              break;
            }
          }
        }

        if (StringUtils.isBlank(localeCode)) {
          localeCode = servletRequest.getLocale().toString();
        }

        if (!localeCode.equals(request.getLocale().toString())) {
          Locale locale;
          String[] localeCodeS = localeCode.split("_");
          if (localeCodeS.length == 2) locale = new Locale(localeCodeS[0], localeCodeS[1]);
          else {
            locale = new Locale(localeCodeS[0]);
          }

          Config.set(
              request,
              Config.FMT_LOCALIZATION_CONTEXT,
              new fi.pyramus.I18N.LocalizationContext(locale));
          servletRequest = new LocaleRequestWrapper((HttpServletRequest) request, locale);
        } else {
          Config.set(
              request,
              Config.FMT_LOCALIZATION_CONTEXT,
              new fi.pyramus.I18N.LocalizationContext(request.getLocale()));
        }
      }
    } finally {
      filterChain.doFilter(servletRequest, response);
    }
  }
예제 #8
0
  public void testJstlLocaleIsSet() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("locale", "es");

    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setSession(new MockHttpSession(null));

    filter.doFilter(request, response, new MockFilterChain());

    assertNotNull(Config.get(request.getSession(), Config.FMT_LOCALE));
  }
예제 #9
0
  /**
   * Gets the default I18N localization context.
   *
   * @param pc Page in which to look up the default I18N localization context
   */
  public static LocalizationContext getLocalizationContext(PageContext pc) {
    LocalizationContext locCtxt = null;

    Object obj = Config.find(pc, Config.FMT_LOCALIZATION_CONTEXT);
    if (obj == null) {
      return null;
    }

    if (obj instanceof LocalizationContext) {
      locCtxt = (LocalizationContext) obj;
    } else {
      // localization context is a bundle basename
      locCtxt = getLocalizationContext(pc, (String) obj);
    }

    return locCtxt;
  }
예제 #10
0
  /**
   * This method looks for a "locale" request parameter. If it finds one, it sets it as the
   * preferred locale and also configures it to work with JSTL.
   *
   * @param request the current request
   * @param response the current response
   * @param chain the chain
   * @throws IOException when something goes wrong
   * @throws ServletException when a communication failure happens
   */
  @SuppressWarnings("unchecked")
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
      int indexOfUnderscore = locale.indexOf('_');
      if (indexOfUnderscore != -1) {
        String language = locale.substring(0, indexOfUnderscore);
        String country = locale.substring(indexOfUnderscore + 1);
        preferredLocale = new Locale(language, country);
      } else {
        preferredLocale = new Locale(locale);
      }
    }

    HttpSession session = request.getSession(false);

    if (session != null) {
      if (preferredLocale == null) {
        preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
      } else {
        session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
        Config.set(session, Config.FMT_LOCALE, preferredLocale);
      }

      if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
        request = new LocaleRequestWrapper(request, preferredLocale);
        LocaleContextHolder.setLocale(preferredLocale);
      }
    }

    String theme = request.getParameter("theme");
    if (theme != null && request.isUserInRole(Constants.ADMIN_ROLE)) {
      Map<String, Object> config = (Map) getServletContext().getAttribute(Constants.CONFIG);
      config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
  }
예제 #11
0
  public int doEndTag() throws JspException {
    TimeZone timeZone = null;

    if (value == null) {
      timeZone = TimeZone.getTimeZone("GMT");
    } else if (value instanceof String) {
      if (((String) value).trim().equals("")) {
        timeZone = TimeZone.getTimeZone("GMT");
      } else {
        timeZone = TimeZone.getTimeZone((String) value);
      }
    } else {
      timeZone = (TimeZone) value;
    }

    if (var != null) {
      pageContext.setAttribute(var, timeZone, scope);
    } else {
      Config.set(pageContext, Config.FMT_TIME_ZONE, timeZone, scope);
    }

    return EVAL_PAGE;
  }
예제 #12
0
  protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Process the POSTed email and password
    String netid = request.getParameter("login_netid");
    String password = request.getParameter("login_password");
    String jsp = null;

    // Locate the eperson
    int status = AuthenticationManager.authenticate(context, netid, password, null, request);

    if (status == AuthenticationMethod.SUCCESS) {
      // Logged in OK.
      Authenticate.loggedIn(context, request, context.getCurrentUser());

      // Set the Locale according to user preferences
      Locale epersonLocale = I18nUtil.getEPersonLocale(context.getCurrentUser());
      context.setCurrentLocale(epersonLocale);
      Config.set(request.getSession(), Config.FMT_LOCALE, epersonLocale);

      log.info(LogManager.getHeader(context, "login", "type=explicit"));

      // resume previous request
      Authenticate.resumeInterruptedRequest(request, response);

      return;
    } else if (status == AuthenticationMethod.CERT_REQUIRED) {
      jsp = "/error/require-certificate.jsp";
    } else {
      jsp = "/login/incorrect.jsp";
    }

    // If we reach here, supplied email/password was duff.
    log.info(
        LogManager.getHeader(
            context, "failed_login", "netid=" + netid + ", result=" + String.valueOf(status)));
    JSPManager.showJSP(request, response, jsp);
  }
예제 #13
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;
  }
예제 #14
0
  /**
   * Obtain a new context object. If a context object has already been created for this HTTP
   * request, it is re-used, otherwise it is created. If a user has authenticated with the system,
   * the current user of the context is set appropriately.
   *
   * @param request the HTTP request
   * @return a context object
   */
  public static Context obtainContext(HttpServletRequest request) throws SQLException {

    // Set encoding to UTF-8, if not set yet
    // This avoids problems of using the HttpServletRequest
    // in the getSpecialGroups() for an AuthenticationMethod,
    // which causes the HttpServletRequest to default to
    // non-UTF-8 encoding.
    try {
      if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
      }
    } catch (Exception e) {
      log.error("Unable to set encoding to UTF-8.", e);
    }

    Context c = (Context) request.getAttribute("dspace.context");

    if (c == null) {
      // No context for this request yet
      c = new Context();
      HttpSession session = request.getSession();

      // See if a user has authentication
      Integer userID = (Integer) session.getAttribute("dspace.current.user.id");

      if (userID != null) {
        String remAddr = (String) session.getAttribute("dspace.current.remote.addr");
        if (remAddr != null && remAddr.equals(request.getRemoteAddr())) {
          EPerson e = EPerson.find(c, userID.intValue());

          Authenticate.loggedIn(c, request, e);
        } else {
          log.warn(
              "POSSIBLE HIJACKED SESSION: request from "
                  + request.getRemoteAddr()
                  + " does not match original "
                  + "session address: "
                  + remAddr
                  + ". Authentication rejected.");
        }
      }

      // Set any special groups - invoke the authentication mgr.
      int[] groupIDs = AuthenticationManager.getSpecialGroups(c, request);

      for (int i = 0; i < groupIDs.length; i++) {
        c.setSpecialGroup(groupIDs[i]);
        log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
      }

      // Set the session ID and IP address
      String ip = request.getRemoteAddr();
      if (useProxies == null) {
        useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
      }
      if (useProxies && request.getHeader("X-Forwarded-For") != null) {
        /* This header is a comma delimited list */
        for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
          if (!request.getHeader("X-Forwarded-For").contains(ip)) {
            ip = xfip.trim();
          }
        }
      }
      c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);

      // Store the context in the request
      request.setAttribute("dspace.context", c);
    }

    // Set the locale to be used
    Locale sessionLocale = getSessionLocale(request);
    Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
    c.setCurrentLocale(sessionLocale);

    return c;
  }
 public static Locale getJstlLocale(PageContext pageContext) {
   Object localeObject = Config.find(pageContext, Config.FMT_LOCALE);
   return (localeObject instanceof Locale ? (Locale) localeObject : null);
 }