@Test
  public void testHttpRequest() {
    Message m = createMessage();
    MessageContext mc = new MessageContextImpl(m);
    HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
    m.put(AbstractHTTPDestination.HTTP_REQUEST, request);

    assertSame(
        request.getClass(),
        ((HttpServletRequestFilter) mc.getHttpServletRequest()).getRequest().getClass());
    assertSame(
        request.getClass(),
        ((HttpServletRequestFilter) mc.getContext(HttpServletRequest.class))
            .getRequest()
            .getClass());
  }
    public Builder session(HttpSession session) {
      if (request == null) {
        request = new NoOpsRequest();
      }

      if (NoOpsRequest.class.isAssignableFrom(request.getClass())) {
        NoOpsRequest.class.cast(request).fake = session;
      } else {
        webSocketFakeSession = session;
      }
      return this;
    }
Exemple #3
0
 public static void change(HttpServletRequest request, HttpServletResponse response) {
   if (LOGGER.isLoggable(Level.FINE)) {
     LOGGER.fine(
         "["
             + request.getRequestURI()
             + "] Changing HttpContext to request "
             + request.getClass().getName()
             + " and response "
             + response.getClass().getName());
   }
   HttpContext context = new HttpContext(request, response);
   CTX.get().offerFirst(context);
 }
  /**
   * Wrap an {@link HttpServletRequest}.
   *
   * @param request {@link HttpServletRequest}
   * @return an {@link AtmosphereRequest}
   */
  public static final AtmosphereRequest wrap(HttpServletRequest request) {
    // Do not rewrap.
    if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {
      return AtmosphereRequestImpl.class.cast(request);
    }

    Builder b = new Builder();
    Enumeration<String> e = request.getAttributeNames();
    String s;
    while (e.hasMoreElements()) {
      s = e.nextElement();
      b.localAttributes.put(s, attributeWithoutException(request, s));
    }
    return b.request(request).build();
  }
  /**
   * For debugging, dump all sorts of information about the request.
   *
   * <p>WARNING: if "req" represents a Multi-part request which has not yet been parsed, then
   * reading these parameters will consume them.
   */
  @SuppressWarnings("unchecked")
  private void dumpRequestDetails(HttpServletRequest req) {
    log.trace("Request is " + req.getClass().getName());

    Map<String, String[]> parms = req.getParameterMap();
    for (Entry<String, String[]> entry : parms.entrySet()) {
      log.trace("Parameter '" + entry.getKey() + "'=" + Arrays.deepToString(entry.getValue()));
    }

    Enumeration<String> attrs = req.getAttributeNames();
    while (attrs.hasMoreElements()) {
      String key = attrs.nextElement();
      String valueString = String.valueOf(req.getAttribute(key));
      String valueOneLine = valueString.replace("\n", " | ");
      log.trace("Attribute '" + key + "'=" + valueOneLine);
    }
  }
 @Override
 public ApiResponse signOutAll() {
   ApiResponse response = ApiResponse.createDefaultApiResponse();
   HttpServletRequest request = HttpUtil.getRequest();
   HttpSession httpSession = HttpUtil.getSession();
   if (request instanceof RequestFacade) {
     Field requestField = null;
     try {
       requestField = request.getClass().getDeclaredField("request");
     } catch (NoSuchFieldException e) {
       e.printStackTrace();
     }
     if (requestField != null) {
       requestField.setAccessible(true);
       Request req = null;
       try {
         req = (Request) requestField.get(request);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       }
       if (req != null) {
         Context context = req.getContext();
         Manager manager = context.getManager();
         Session[] sessions = manager.findSessions();
         if (sessions != null) {
           for (Session session : sessions) {
             if (!httpSession.getId().equals(session.getId())) {
               session.expire();
             }
           }
         }
       }
     }
   }
   return response;
 }
  /**
   * Check the response - is it a response to the login page ?
   *
   * @return A boolean indicating whether to continue with the request or not
   */
  @Override
  protected boolean validatePossibleAuthenticationResponse(
      HttpServletRequest request, final HttpServletResponse response, final String pathRequested)
      throws ServletException, IOException {
    // Check if this is a j_security_check uri
    if (pathRequested.endsWith(FormAuthenticationHandler.FORM_ACTION)) {
      final String username = request.getParameter(FormAuthenticationHandler.FORM_USER);
      final String password = request.getParameter(FormAuthenticationHandler.FORM_PASS);

      // Send to error page if invalid
      final AuthenticationPrincipal principal =
          realm.authenticateByUsernamePassword(username, password);
      if (principal == null) {
        final javax.servlet.RequestDispatcher rdError = request.getRequestDispatcher(errorPage);
        rdError.forward(request, response);
      } // Send to stashed request
      else {
        // Iterate back as far as we can
        ServletRequest wrapperCheck = request;
        while (wrapperCheck instanceof HttpServletRequestWrapper) {
          wrapperCheck = ((HttpServletRequestWrapper) wrapperCheck).getRequest();
        }

        // Get the stashed request
        WinstoneRequest actualRequest = null;
        if (wrapperCheck instanceof WinstoneRequest) {
          actualRequest = (WinstoneRequest) wrapperCheck;
          actualRequest.setRemoteUser(principal);
        } else {
          FormAuthenticationHandler.logger.warn(
              "Request type invalid - can't set authenticated user in request class: {}",
              wrapperCheck.getClass().getName());
        }
        final HttpSession session = request.getSession(Boolean.TRUE);
        String previousLocation = loginPage;
        final RetryRequestParams cachedRequest =
            (RetryRequestParams) session.getAttribute(FormAuthenticationHandler.CACHED_REQUEST);
        if ((cachedRequest != null) && (actualRequest != null)) {
          // Repopulate this request from the params we saved
          request = new RetryRequestWrapper(request, cachedRequest);
          previousLocation =
              (request.getServletPath() == null ? "" : request.getServletPath())
                  + (request.getPathInfo() == null ? "" : request.getPathInfo());
        } else {
          FormAuthenticationHandler.logger.debug(
              "No cached request - redirecting to the login page.");
        }

        // do role check, since we don't know that this user has
        // permission
        if (doRoleCheck(request, response, previousLocation)) {
          principal.setAuthType(HttpServletRequest.FORM_AUTH);
          session.setAttribute(FormAuthenticationHandler.AUTHENTICATED_USER, principal);
          final javax.servlet.RequestDispatcher rdPrevious =
              request.getRequestDispatcher(previousLocation);
          rdPrevious.forward(request, response);
        } else {
          final javax.servlet.RequestDispatcher rdError = request.getRequestDispatcher(errorPage);
          rdError.forward(request, response);
        }
      }
      return Boolean.FALSE;
    } // If it's not a login, get the session, and look up the auth user
    // variable
    else {
      WinstoneRequest actualRequest = null;
      if (request instanceof WinstoneRequest) {
        actualRequest = (WinstoneRequest) request;
      } else if (request instanceof HttpServletRequestWrapper) {
        final HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper) request;
        if (wrapper.getRequest() instanceof WinstoneRequest) {
          actualRequest = (WinstoneRequest) wrapper.getRequest();
        } else {
          FormAuthenticationHandler.logger.warn(
              "Request type invalid - can't set authenticated user in request class: {}",
              wrapper.getRequest().getClass().getName());
        }
      } else {
        FormAuthenticationHandler.logger.warn(
            "Request type invalid - can't set authenticated user in request class: {}",
            request.getClass().getName());
      }

      final HttpSession session = actualRequest.getSession(Boolean.FALSE);
      if (session != null) {
        final AuthenticationPrincipal authenticatedUser =
            (AuthenticationPrincipal)
                session.getAttribute(FormAuthenticationHandler.AUTHENTICATED_USER);
        if (authenticatedUser != null) {
          actualRequest.setRemoteUser(authenticatedUser);
          FormAuthenticationHandler.logger.debug("Got authenticated user from session");
        }
      }
      return Boolean.TRUE;
    }
  }
  /**
   * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned
   * AtmosphereRequest is not destroyable.
   *
   * @param request {@link HttpServletRequest}
   * @return an {@link AtmosphereRequest}
   */
  public static final AtmosphereRequest cloneRequest(
      HttpServletRequest request,
      boolean loadInMemory,
      boolean copySession,
      boolean isDestroyable,
      boolean createSession) {
    Builder b;
    HttpServletRequest r;

    Cookie[] cs = request.getCookies();
    Set<Cookie> hs = Collections.synchronizedSet(new HashSet());
    if (cs != null) {
      for (Cookie c : cs) {
        hs.add(c);
      }
    }

    boolean isWrapped = false;
    if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {
      b = AtmosphereRequestImpl.class.cast(request).b;
      isWrapped = true;
    } else {
      b = new Builder();
      b.request(request);
    }

    HttpSession session = null;
    if (copySession) {
      session = request.getSession(createSession);
      if (session != null) {
        session = new FakeHttpSession(session);
      } else {
        session = new FakeHttpSession("", null, System.currentTimeMillis(), -1);
      }
    }

    b.servletPath(request.getServletPath())
        .pathInfo(request.getPathInfo())
        .contextPath(request.getContextPath())
        .requestURI(request.getRequestURI())
        .requestURL(request.getRequestURL().toString())
        .method(request.getMethod())
        .serverName(request.getServerName())
        .serverPort(request.getServerPort())
        .remoteAddr(request.getRemoteAddr())
        .remoteHost(request.getRemoteHost())
        .remotePort(request.getRemotePort())
        .destroyable(isDestroyable)
        .cookies(hs)
        .session(session)
        .principal(request.getUserPrincipal())
        .authType(request.getAuthType())
        .isSSecure(request.isSecure());

    if (loadInMemory) {
      String s =
          (String)
              attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);
      boolean throwException = s != null && Boolean.parseBoolean(s);
      r = new NoOpsRequest(throwException);
      if (isWrapped) {
        load(b.request, b);
      } else {
        load(request, b);
      }
      b.request(r);
    }

    return isWrapped ? AtmosphereRequestImpl.class.cast(request) : b.build();
  }
  private ModelAndView uploadFileBySwfUpload(
      HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> model = new HashMap<String, Object>();
    List<String> uploadedFiles = new ArrayList<String>();
    String uploadMsg = "";
    String filePath = null;
    String mediaType = null;
    if (multipartResolver.isMultipart(request)) {
      MultipartHttpServletRequest fileRequest = null;
      try {
        fileRequest = multipartResolver.resolveMultipart(request);
        Iterator<String> iter = fileRequest.getFileNames();
        mediaType = getParameter(request, "mediaType", "other");
        String objId = getParameter(request, "objId", null);
        while (iter.hasNext()) {
          String prmName = iter.next();
          MultipartFile file = fileRequest.getFile(prmName);
          if (file.isEmpty()) {
            continue;
          }
          if (file.getSize() > maxUploadSize) {
            uploadMsg = "err001";
            continue;
          }
          ImageConf imageConf = uploadManager.getImageConf(mediaType);
          if (imageConf == null) {
            imageConf = uploadManager.getImageConf("other");
          }
          String fileName = file.getOriginalFilename();
          String fileImageSize = getParameter(request, "fileImageSize", null);
          FileInfo fileInfo = null;
          if (fileImageSize == null || mediaType.equals("other") || mediaType.equals("a_and_d")) {
            fileInfo =
                new FileInfo(
                    imageConf.getMediaType(),
                    imageConf.getOriginalImageCategory(),
                    fileName,
                    objId);
          } else {
            fileInfo = new FileInfo(imageConf.getMediaType(), fileImageSize, fileName, objId);
          }
          File pfile = null;
          boolean fileExists = false;
          if (isUuidRename) {
            fileInfo.uuidRename();
          }
          do {
            filePath = getFullFilePath(fileInfo.getMediaPath());
            pfile = new File(filePath);
            fileExists = pfile.exists();
            if (fileExists) {
              if (isUuidRename) {
                fileInfo.uuidRename();
              } else {
                logger.info(formatMsg("File already exists: %1, auto rename...", filePath));
                fileInfo.autoRename();
              }
            }
          } while (fileExists);
          pfile.mkdirs();
          file.transferTo(pfile);
          // 处理缩放和水印,并删除原文件
          uploadManager.processImage(pfile, imageConf, fileInfo);
          // 不管什么情况下,都只返回原图的url就可以。
          uploadedFiles.add(fileInfo.getSampleMediaPath());
        }
      } catch (Throwable ex) {
        uploadMsg = "err002";
        logger.error(
            formatMsg(
                "Unexpected error when handling uploaded file %1, cause is: %2.",
                filePath, ex.getMessage()),
            ex);
      } finally {
        if (fileRequest != null) {
          multipartResolver.cleanupMultipart(fileRequest);
        }
      }
    } else {
      uploadMsg = "err002";
      logger.warn(
          "Invalid request, MultipartHttpServletRequest expected, found: "
              + request.getClass().getName()
              + ".\n"
              + RequestUtil.getRequestInfo(request));
    }

    model.put("url", uploadedFiles.get(0));
    model.put("mediaType", mediaType);
    model.put("msg", uploadMsg);
    JSONObject jsonMap = JSONObject.fromObject(model);
    try {
      response.getWriter().print(jsonMap.toString());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }