Example #1
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   request.setCharacterEncoding(encoding);
   response.setCharacterEncoding(encoding);
   chain.doFilter(request, response);
 }
Example #2
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rpo = (HttpServletResponse) response;
    javax.servlet.http.HttpSession session = req.getSession();

    try {
      req.setCharacterEncoding("utf-8");
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    String userId = (String) session.getAttribute("username");
    if (userId != null) {
      try {
        chain.doFilter(request, response);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      try {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print("{'success':false,'msg':'未登录或登录失效'}");
        out.flush();
        out.close();
        // rpo.sendRedirect("/login.jsp");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Example #3
0
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   // 设置字符过滤
   request.setCharacterEncoding(this.charset);
   response.setCharacterEncoding(this.charset);
   chain.doFilter(request, response);
 }
 @Override
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws IOException, ServletException {
   req.setCharacterEncoding("UTF-8");
   resp.setCharacterEncoding("UTF-8");
   chain.doFilter(req, resp);
 }
Example #5
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    String path = httpRequest.getServletPath();
    HasRolePrincipal principal = getPrincipal(httpRequest);
    PrincipalRequestWrapper requestWrapper = new PrincipalRequestWrapper(httpRequest, principal);

    if (securityResources.containsKey(path)) {
      if (principal.isNull()) {
        httpRequest.getRequestDispatcher("/login").forward(requestWrapper, servletResponse);
        return;
      }

      Set<String> roles = securityResources.get(path);
      if (Sets.intersection(roles, principal.getRoles()).isEmpty()) {
        ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_FORBIDDEN);
        servletResponse.setCharacterEncoding("UTF-8");
        requestWrapper.getRequestDispatcher("/403.jsp").include(requestWrapper, servletResponse);
        return;
      }
    }

    filterChain.doFilter(requestWrapper, servletResponse);
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
      throw new ServletException("Only HttpServletRequest requests are supported");
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // extract the callback method from the request query parameters
    String callback = getCallbackMethod(httpRequest);

    if (!isJSONPRequest(callback)) {
      // Request is not a JSONP request move on
      chain.doFilter(request, response);
    } else {
      // Need to check if the callback method is safe
      if (!SAFE_PRN.matcher(callback).matches()) {
        throw new ServletException(
            "JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
      }

      // Will stream updated response
      final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      // Create a custom response wrapper to adding in the padding
      HttpServletResponseWrapper responseWrapper =
          new HttpServletResponseWrapper(httpResponse) {

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
              return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                  byteStream.write(b);
                }
              };
            }

            @Override
            public PrintWriter getWriter() throws IOException {
              return new PrintWriter(byteStream);
            }
          };

      // Process the rest of the filter chain, including the JAX-RS request
      chain.doFilter(request, responseWrapper);

      // Override response content and encoding
      response.setContentType(CONTENT_TYPE);
      response.setCharacterEncoding("UTF-8");

      // Write the padded updates to the output stream.
      response.getOutputStream().write((callback + "(").getBytes());
      response.getOutputStream().write(byteStream.toByteArray());
      response.getOutputStream().write(");".getBytes());
    }
  }
Example #7
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   request.setCharacterEncoding(CHARSET);
   response.setCharacterEncoding(CHARSET);
   // response.setContentType("text/html; charset=" + CHARSET);
   chain.doFilter(request, response);
 }
Example #8
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   // TODO Auto-generated method stub
   request.setCharacterEncoding("UTF-8");
   response.setCharacterEncoding("UTF-8");
   chain.doFilter(request, response);
 }
Example #9
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   request.setCharacterEncoding(charset);
   response.setCharacterEncoding(charset);
   EncodeHttpServletRequest enRequest = new EncodeHttpServletRequest(request);
   chain.doFilter(enRequest, response);
 }
 /** set character encoding utf-8; */
 public void doFilter(ServletRequest rep, ServletResponse resp, FilterChain filterChain)
     throws IOException, ServletException {
   //		System.out.println("utf-8");
   rep.setCharacterEncoding("utf-8");
   resp.setCharacterEncoding("utf-8");
   //		System.out.println(rep.getParameter("id"));
   filterChain.doFilter(rep, resp);
 }
Example #11
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   if (StringUtils.isNotBlank(encoding)) {
     request.setCharacterEncoding(encoding);
     response.setCharacterEncoding(encoding);
   }
   chain.doFilter(request, response);
 }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
     throws IOException, ServletException {
   if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
     request.setCharacterEncoding(this.encoding);
     if (this.forceEncoding && responseSetCharacterEncodingAvailable) {
       response.setCharacterEncoding(this.encoding);
     }
   }
   filterChain.doFilter(request, response);
 }
Example #13
0
 /**
  * @param request The servlet request we are processing
  * @param response The servlet response we are creating
  * @param chain The filter chain we are processing
  * @exception IOException if an input/output error occurs
  * @exception ServletException if a servlet error occurs
  */
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   String encoding = this.filterConfig.getInitParameter("encoding");
   // 请求编码设置
   request.setCharacterEncoding(encoding);
   // 响应编码设置
   response.setCharacterEncoding(encoding);
   chain.doFilter(request, response);
 }
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws ServletException, IOException {
    String codeRequest = req.getCharacterEncoding();

    // set encoding type from parameters if not set
    if (encoding != null && !encoding.equalsIgnoreCase(codeRequest)) {
      req.setCharacterEncoding(encoding);
      resp.setCharacterEncoding(encoding);
    }
    chain.doFilter(req, resp);
  }
 public String execute() throws IOException {
   ArrayList<MeetingRoom> tran;
   ServletResponse response = ServletActionContext.getResponse();
   response.setCharacterEncoding("utf-8");
   PrintWriter out = response.getWriter();
   DeleteMeetingRoomService show = new DeleteMeetingRoomService();
   tran = show.Showlist();
   JSONArray jsonArray = JSONArray.fromObject(tran);
   out.print(jsonArray);
   return null;
 }
Example #16
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(this.encoding);
    PrintWriter out = res.getWriter();
    out.print("编码格式:" + this.encoding + "<br/>");
    chain.doFilter(request, response);
  }
Example #17
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    servletResponse.setContentType(TYPE);
    servletRequest.setCharacterEncoding(ENCODING);

    servletResponse.setContentType(TYPE);
    servletResponse.setCharacterEncoding(ENCODING);

    filterChain.doFilter(servletRequest, servletResponse);
  }
 @Override
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws ServletException, IOException {
   String requestEncoding = req.getCharacterEncoding();
   if (initParamEncoding != null && !initParamEncoding.equalsIgnoreCase(requestEncoding)) {
     req.setCharacterEncoding(initParamEncoding);
     resp.setCharacterEncoding(initParamEncoding);
   }
   resp.setContentType("UTF-8");
   logger.debug("CharacterEncoding was set");
   chain.doFilter(req, resp);
 }
Example #19
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
      throws IOException, ServletException {
    // Respect the client-specified character encoding
    // (see HTTP specification section 3.4.1)
    if (null == request.getCharacterEncoding()) request.setCharacterEncoding(encoding);

    /** Set the default response content type and encoding */
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    next.doFilter(request, response);
  }
  /**
   * Select and set (if specified) the character encoding to be used to interpret request parameters
   * for this request.
   *
   * @param request The servlet request we are processing
   * @param result The servlet response we are creating
   * @param chain The filter chain we are processing
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet error occurs
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
      String encoding = selectEncoding(request);
      if (encoding != null) {
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
      }
    }

    // Pass control on to the next filter
    chain.doFilter(request, response);
  }
Example #21
0
  /**
   * ***********************************************************************
   *
   * <p>***********************************************************************
   */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String servletPath = ((HttpServletRequest) request).getServletPath();
    // log.info ("ServletPath: " + servletPath);
    // log.info ("RealPath:    " + servletContext.getRealPath (servletPath));
    // log.info ("MimeType:    " + servletContext.getMimeType (servletContext.getRealPath
    // (servletPath)));
    String mimeType = servletContext.getMimeType(servletContext.getRealPath(servletPath));
    if (mimeType == null) {
      response.setContentType("text/plain");
    }
    response.setCharacterEncoding("UTF-8");
    defaultRequestDispatcher.forward(request, response);
  }
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    if (!this.isAjaxRequest(httpServletRequest)) {
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {
      response.setCharacterEncoding(Constants.BASE_ENCODING);
      response.setContentType("application/json");
      response.getWriter().write(Constants.NO_AUTHZ_JSON_DATA);
    }
    return false;
  }
Example #23
0
  /** Sets up the charset for the request and response based on
   * {@link #getPreferredLocale(HttpSession,ServletRequest)}. After setting up, you shall invoke
   * {@link #cleanup} before exiting.
   *
   * <pre><code> final Object old = setup(request, response, null);
   * try {
   *	  ....
   * } finally {
   *    cleanup(request, old);
   * }
   *
   * <p>It is OK to call this method multiple time, since it is smart
   * enough to ignore redundant calls.
   *
   * <p>{@link CharsetFilter} actually use this method to setup
   * the proper charset and locale. By mapping {@link CharsetFilter} to
   * all servlets, the encoding charset could be prepared correctly.
   * However, if you are writing libraries to be as independent of
   * web.xml as possible, you might choose to invoke this method directly.
   *
   * @param sess the session to look for the preferred locale. Ignored if null.
   * @param charset the response's charset. If null or empty,
   * response.setCharacterEncoding won't be called, i.e., the container's
   * default is used.
   * @return an object that must be passed to {@link #cleanup}
   */
  public static final Object setup(
      HttpSession sess, ServletRequest request, ServletResponse response, String charset) {
    if (hasSetup(request)) // processed before?
    return Objects.UNKNOWN;

    final Locale locale = getPreferredLocale(sess, request);
    response.setLocale(locale);
    if (charset != null && charset.length() > 0) {
      try {
        if (Servlets.isServlet24()) {
          response.setCharacterEncoding(charset);
        } else {
          // don't access 2.4 API: setCharacterEncoding, getContentType
          response.setContentType(";charset=" + charset);
        }
      } catch (Throwable ex) {
        try {
          final String v = response.getCharacterEncoding();
          if (!Objects.equals(v, charset))
            log.warn("Unable to set response's charset: " + charset + " (current=" + v + ')', ex);
        } catch (Throwable t) { // just in case
        }
      }
    }

    if (request.getCharacterEncoding() == null) {
      charset = response.getCharacterEncoding();
      try {
        request.setCharacterEncoding(charset);
      } catch (Throwable ex) {
        final String v = request.getCharacterEncoding();
        if (!Objects.equals(v, charset))
          log.warn(
              "Unable to set request's charset: "
                  + charset
                  + " (current="
                  + v
                  + "): "
                  + Exceptions.getMessage(ex));
      }
    }

    markSetup(request, true);
    return Locales.setThreadLocal(locale);
  }
Example #24
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    HttpServletRequest httpReq = (HttpServletRequest) req;
    String lang = httpReq.getParameter("lang");
    if (lang != null && !lang.isEmpty()) {
      ThreadLocalLocaleHolder.set(new Locale(lang));
    } else if ((lang = (String) httpReq.getSession().getAttribute("lang")) != null) {
      ThreadLocalLocaleHolder.set(new Locale(lang));
    }
    httpReq.getSession().setAttribute("lang", ThreadLocalLocaleHolder.get().getLanguage());

    chain.doFilter(req, res);
  }
 protected void redirectToLogin(ServletRequest request, ServletResponse response)
     throws IOException {
   if (isAjaxRequest((HttpServletRequest) request)) {
     response.setCharacterEncoding(Constants.BASE_ENCODING);
     response.setContentType("application/json");
     response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
     return;
   }
   if (this.isIframeMode((HttpServletRequest) request)) { // iframe 不要導向 login.action 因為畫面會怪怪的    	
     WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
     return;
   }
   if (this.isDojoxContentPane(
       (HttpServletRequest) request)) { // 在 dojox.layout.ContentPane 不要出現 login.action 頁面    	
     WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
     return;
   }
   WebUtils.issueRedirect(request, response, getLoginUrl());
 }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    try {

      @SuppressWarnings("static-access")
      HttpSession session = util.request().getSession();

      Admin admin = (Admin) session.getAttribute("admin");

      if (admin == null) {
        request.setCharacterEncoding("GBK");
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        String loginPage = "/PerfectBefriend/SuperAdmin/SuperAdmin.jsp";
        StringBuilder builder = new StringBuilder();
        builder.append("<script type=\"text/javascript\">");
        builder.append("alert('no');");
        builder.append("window.top.location.href='");
        builder.append(loginPage);
        builder.append("';");
        builder.append("</script>");
        out.print(builder.toString());
      } else {

        if (admin.getLevel() == 1 || admin.getLevel() == 3) {
          chain.doFilter(request, response);

        } else {

          util.Out().println("no");
        }
      }

    } catch (Exception e) {
      util.Out().println(e.getMessage());
    }
  }
Example #27
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (ExtendManager.hasAction("BeforeSSIFilter")) {
      ExtendManager.executeAll("BeforeSSIFilter", new Object[] {request, response, chain});
    }

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if ((Config.ServletMajorVersion == 2) && (Config.ServletMinorVersion == 3))
      response.setContentType("text/html;charset=" + Constant.GlobalCharset);
    else {
      response.setCharacterEncoding(Constant.GlobalCharset);
    }
    request.setCharacterEncoding(Constant.GlobalCharset);

    req.setAttribute("org.apache.catalina.ssi.SSIServlet", "true");

    ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
    ResponseIncludeWrapper responseIncludeWrapper =
        new ResponseIncludeWrapper(this.config.getServletContext(), req, res, basos);

    chain.doFilter(req, responseIncludeWrapper);

    responseIncludeWrapper.flushOutputStreamOrWriter();
    byte[] bytes = basos.toByteArray();

    String encoding = res.getCharacterEncoding();

    SSIExternalResolver ssiExternalResolver =
        new SSIServletExternalResolver(
            this.config.getServletContext(),
            req,
            res,
            this.isVirtualWebappRelative,
            this.debug,
            encoding);
    SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, this.debug);

    Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding);
    ByteArrayOutputStream ssiout = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding));

    long lastModified =
        ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer);

    writer.flush();
    bytes = ssiout.toByteArray();

    if (this.expires != null) {
      res.setDateHeader("expires", new Date().getTime() + this.expires.longValue() * 1000L);
    }
    if (lastModified > 0L) {
      res.setDateHeader("last-modified", lastModified);
    }
    res.setContentLength(bytes.length);

    res.setContentType("text/html;charset=" + Constant.GlobalCharset);
    try {
      OutputStream out = res.getOutputStream();
      out.write(bytes);
    } catch (Throwable t) {
      Writer out = res.getWriter();
      out.write(new String(bytes));
    }
  }
Example #28
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws ServletException, IOException {

    if (!Aura.getConfigAdapter().isTestAllowed()) {
      chain.doFilter(req, res);
      return;
    }

    TestContextAdapter testContextAdapter = Aura.get(TestContextAdapter.class);
    if (testContextAdapter == null) {
      chain.doFilter(req, res);
      return;
    }

    // Check for requests to execute a JSTest, i.e. initial component GETs with particular
    // parameters.
    HttpServletRequest request = (HttpServletRequest) req;
    if ("GET".equals(request.getMethod())) {
      String contextPath = request.getContextPath();
      String uri = request.getRequestURI();
      String browserType = request.getParameter("aura.browserType");
      if (browserType == null) {
        // read it from request header
        String ua = request.getHeader(HttpHeaders.USER_AGENT);
        if (ua != null) {
          ua = ua.toLowerCase();
          if (ua.contains("chrome")) {
            browserType = "GOOGLECHROME";
          } else if (ua.contains("safari")) {
            browserType = "SAFARI";
          } else if (ua.contains("firefox")) {
            browserType = "FIREFOX";
          } else if (ua.contains("ipad")) {
            browserType = "IPAD";
          } else if (ua.contains("iphone")) {
            browserType = "IPHONE";
          } else if (ua.contains("msie 10")) {
            browserType = "IE10";
          } else if (ua.contains("msie 9")) {
            browserType = "IE9";
          } else if (ua.contains("msie 8")) {
            browserType = "IE8";
          } else if (ua.contains("msie 7")) {
            browserType = "IE7";
          } else if (ua.contains("msie 6")) {
            browserType = "IE6";
          } else if (ua.contains("trident/7.0")) {
            browserType = "IE11";
          } else if (ua.contains("edge/12")) {
            browserType = "IE12";
          } else {
            browserType = "OTHER";
          }
        }
      }
      String path;
      if (uri.startsWith(contextPath)) {
        path = uri.substring(contextPath.length());
      } else {
        path = uri;
      }
      Matcher matcher = AuraRewriteFilter.DESCRIPTOR_PATTERN.matcher(path);
      if (matcher.matches()) {
        // Extract the target component since AuraContext usually does not have the app descriptor
        // set yet.
        DefType type = "app".equals(matcher.group(3)) ? DefType.APPLICATION : DefType.COMPONENT;
        String namespace = matcher.group(1);
        String name = matcher.group(2);
        DefDescriptor<?> targetDescriptor =
            Aura.getDefinitionService()
                .getDefDescriptor(
                    String.format("%s:%s", namespace, name), type.getPrimaryInterface());

        // Check if a single jstest is being requested.
        String testToRun = jstestToRun.get(request);
        if (testToRun != null && !testToRun.isEmpty()) {
          AuraContext context = Aura.getContextService().getCurrentContext();
          Format format = context.getFormat();
          switch (format) {
            case HTML:
              TestCaseDef testDef;
              TestContext testContext;
              String targetUri;
              try {
                TestSuiteDef suiteDef = getTestSuite(targetDescriptor);
                testDef = getTestCase(suiteDef, testToRun);
                testDef.validateDefinition();
                testDef.setCurrentBrowser(browserType);
                testContextAdapter.getTestContext(testDef.getQualifiedName());
                testContextAdapter.release();
                testContext = testContextAdapter.getTestContext(testDef.getQualifiedName());
                targetUri = buildJsTestTargetUri(targetDescriptor, testDef);
              } catch (QuickFixException e) {
                ((HttpServletResponse) res).setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
                res.getWriter().append(e.getMessage());
                Aura.getExceptionAdapter().handleException(e);
                return;
              }

              // Load any test mocks.
              Collection<Definition> mocks = testDef.getLocalDefs();
              testContext.getLocalDefs().addAll(mocks);
              loadTestMocks(context, true, testContext.getLocalDefs());

              // Capture the response and inject tags to load jstest.
              String capturedResponse = captureResponse(req, res, targetUri);
              if (capturedResponse != null) {
                res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
                if (!Aura.getContextService().isEstablished()) {
                  // There was an error in the original response, so just write the response out.
                  res.getWriter().write(capturedResponse);
                } else {
                  String testTag =
                      buildJsTestScriptTag(targetDescriptor, testToRun, capturedResponse);
                  injectScriptTags(res.getWriter(), capturedResponse, testTag);
                }
                return;
              }
            case JS:
              res.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING);
              writeJsTestScript(res.getWriter(), targetDescriptor, testToRun);
              return;
            default:
              // Pass it on.
          }
        }

        // aurajstest:jstest app is invokable in the following ways:
        // ?aura.mode=JSTEST - run all tests
        // ?aura.mode JSTEST&test=XXX - run single test
        // ?aura.jstest - run all tests
        // ?aura.jstest=XXX - run single test
        // ?aura.jstestrun - run all tests
        // TODO: delete JSTEST mode
        String jstestAppRequest = jstestAppFlag.get(request);
        Mode mode = AuraContextFilter.mode.get(request, Mode.PROD);
        if (mode == Mode.JSTEST
            || mode == Mode.JSTESTDEBUG
            || jstestAppRequest != null
            || testToRun != null) {

          mode = mode.toString().endsWith("DEBUG") ? Mode.AUTOJSTESTDEBUG : Mode.AUTOJSTEST;

          String qs = String.format("descriptor=%s:%s&defType=%s", namespace, name, type.name());
          String testName = null;
          if (jstestAppRequest != null && !jstestAppRequest.isEmpty()) {
            testName = jstestAppRequest;
          } else if (testToRun != null && !testToRun.isEmpty()) {
            testName = testToRun;
          }
          if (testName != null) {
            qs = qs + "&test=" + testName;
          }

          String newUri =
              createURI(
                  "aurajstest",
                  "jstest",
                  DefType.APPLICATION,
                  mode,
                  Authentication.AUTHENTICATED.name(),
                  qs);
          RequestDispatcher dispatcher =
              servletContext.getContext(newUri).getRequestDispatcher(newUri);
          if (dispatcher != null) {
            dispatcher.forward(req, res);
            return;
          }
        }
      }
    }

    // Handle mock definitions specified in the tests.
    TestContext testContext = getTestContext(request);
    if (testContext == null) {
      // During manual testing, the test context adapter may not always get cleared.
      testContextAdapter.clear();
    } else {
      ContextService contextService = Aura.getContextService();
      if (!contextService.isEstablished()) {
        LOG.error("Aura context is not established! New context will NOT be created.");
        chain.doFilter(req, res);
        return;
      }
      AuraContext context = contextService.getCurrentContext();

      // Reset mocks if requested, or for the initial GET.
      boolean doResetMocks = testReset.get(request, Format.HTML.equals(context.getFormat()));
      loadTestMocks(context, doResetMocks, testContext.getLocalDefs());
    }
    chain.doFilter(req, res);
  }
Example #29
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // 设置基本信息
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    /*request.setCharacterEncoding("GBK");
    response.setCharacterEncoding("GBK");*/
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    // 打印请求的 URL 到控制台
    urlFilter(httpServletRequest);

    // 只有登陆后才可以访问 /user/ 路径下面的jsp和servlet
    String requestURL = httpServletRequest.getRequestURL().toString();
    String loginPage = "userlogin";
    String registerPage = "userregister";

    // 是否是注册请求
    boolean isRegister =
        requestURL.contains(registerPage) || requestURL.contains("/modules/user/jsp/userregister");
    // 是否是登陆请求
    boolean isLogin =
        requestURL.contains("/modules/user/jsp/userlogin") || requestURL.contains(loginPage);
    // 是否是登陆请求管理员
    boolean isManage =
        requestURL.contains("/modules/admin/jsp/adminlogin") || requestURL.contains("adminlogin");
    // 是否是访问管理员下的目录
    boolean isAdminPages = requestURL.contains("/modules/admin") || requestURL.contains("Admin");
    if (isRegister) {
      System.out.println("请求注册用户");
      httpServletRequest
          .getRequestDispatcher("modules/user/jsp/register.jsp")
          .forward(httpServletRequest, response);
    } else if (isLogin) {
      // 得到user的对象,为空则没有登陆跳转到登陆界面,不为空就是登陆的继续执行
      System.out.println("请求登陆用户:");
      User user = (User) httpServletRequest.getSession().getAttribute("User");
      if (user == null) {
        httpServletRequest
            .getRequestDispatcher("/modules/user/jsp/login.jsp")
            .forward(httpServletRequest, response);
      } else chain.doFilter(httpServletRequest, response);
    } else if (isManage) {
      System.out.println("请求登陆管理员");
      Operator operator = (Operator) httpServletRequest.getSession().getAttribute("Operator");
      if (operator == null) {
        System.out.println("管理员为空");
        httpServletRequest
            .getRequestDispatcher("/modules/admin/jsp/AdminLogin.jsp")
            .forward(httpServletRequest, response);
      } else chain.doFilter(httpServletRequest, response);
    } /*else if (isAdminPages) {
      	System.out.println("正在访问管理员下pages");
      	// 判断operator 在session中是否过期,如果过期就跳转到管理员登陆界面
      	Operator operator = (Operator) httpServletRequest.getSession().getAttribute("Operator");
      	if (operator == null) {
      		// 可以打印“ 信息已过期 请重新登陆 ”
      		System.out.println("管理员已过期");
      		httpServletRequest.getRequestDispatcher("/modules/admin/jsp/AdminLogin.jsp").forward(httpServletRequest, response);
      	}else {
      		chain.doFilter(httpServletRequest, response);
      	}
      }*/ else {
      chain.doFilter(httpServletRequest, response);
    }
  }
Example #30
0
  /**
   * Try to write response from cache.
   *
   * @param request the specified request
   * @param response the specified response
   * @param chain filter chain
   * @throws IOException io exception
   * @throws ServletException servlet exception
   */
  @Override
  public void doFilter(
      final ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final long startTimeMillis = System.currentTimeMillis();
    request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis);

    final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    final String requestURI = httpServletRequest.getRequestURI();
    LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI);

    if (StaticResources.isStatic(httpServletRequest)) {
      final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo();
      LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path);
      request.getRequestDispatcher(path).forward(request, response);

      return;
    }

    if (!Latkes.isPageCacheEnabled()) {
      LOGGER.log(Level.FINEST, "Page cache is disabled");
      chain.doFilter(request, response);

      return;
    }

    final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
    if ("mobile".equals(skinDirName)) {
      // Mobile request, bypasses page caching
      chain.doFilter(request, response);

      return;
    }

    String pageCacheKey;
    final String queryString = httpServletRequest.getQueryString();
    pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY);
    if (Strings.isEmptyOrNull(pageCacheKey)) {
      pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString);
      request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey);
    }

    final JSONObject cachedPageContentObject =
        PageCaches.get(pageCacheKey, httpServletRequest, (HttpServletResponse) response);

    if (null == cachedPageContentObject) {
      LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI);
      chain.doFilter(request, response);

      return;
    }

    final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE);

    try {
      // If cached an article that has view password, dispatches the password form
      if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType)
          && cachedPageContentObject.has(PageCaches.CACHED_PWD)) {
        JSONObject article = new JSONObject();

        final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID);

        article.put(Keys.OBJECT_ID, articleId);
        article.put(
            Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD));

        if (articles.needViewPwd(httpServletRequest, article)) {
          article = articleRepository.get(articleId); // Loads the article entity

          final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
          try {
            httpServletResponse.sendRedirect(
                Latkes.getServePath()
                    + "/console/article-pwd"
                    + articles.buildArticleViewPwdFormParameters(article));
            return;
          } catch (final Exception e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
          }
        }
      }
    } catch (final Exception e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }

    try {
      LOGGER.log(
          Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey);
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
      final PrintWriter writer = response.getWriter();
      String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT);
      final String topBarHTML =
          TopBars.getTopBarHTML((HttpServletRequest) request, (HttpServletResponse) response);
      cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML);

      final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE);
      LOGGER.log(
          Level.FINEST,
          "Cached value[key={0}, type={1}, title={2}]",
          new Object[] {pageCacheKey, cachedType, cachedTitle});

      statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response);

      final long endimeMillis = System.currentTimeMillis();
      final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
      final String msg =
          String.format(
              "<!-- Cached by B3log Solo(%1$d ms), %2$s -->",
              endimeMillis - startTimeMillis, dateString);
      LOGGER.finer(msg);
      cachedPageContent += Strings.LINE_SEPARATOR + msg;
      writer.write(cachedPageContent);
      writer.flush();
      writer.close();
    } catch (final JSONException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final RepositoryException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    } catch (final ServiceException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      chain.doFilter(request, response);
    }
  }