Ejemplo n.º 1
0
 static String rebuildUri(HttpServletRequest request, String redirectUrlPrefix) {
   HttpSession session = ((HttpServletRequest) request).getSession(true);
   StringBuilder url = new StringBuilder();
   if (redirectUrlPrefix.endsWith("/")) {
     redirectUrlPrefix = redirectUrlPrefix.substring(0, redirectUrlPrefix.length() - 1);
   }
   url.append(redirectUrlPrefix);
   String uri = request.getRequestURI().substring(request.getContextPath().length());
   url.append(uri);
   url.append("?");
   if (request.getQueryString() != null) {
     url.append(request.getQueryString());
     url.append("&");
   }
   url.append(ssoKey);
   url.append("=");
   try {
     url.append(
         RmStringHelper.encodeUrl(
             RmCryptoHelper.encryptDesBase64(
                 RmSsoLogin.createInstance(session.getId()).toString())));
   } catch (Exception e) {
     e.printStackTrace();
   }
   return url.toString();
 }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws ServletException, IOException {

    long start = System.currentTimeMillis();
    try {
      log.info(
          "Request: {} {}",
          request.getMethod(),
          request.getQueryString() == null
              ? request.getRequestURI()
              : request.getRequestURI() + "?" + request.getQueryString());
      log.info("Remote host: {} {}", request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
      log.info("User-Agent: {}", request.getHeader("User-Agent"));

      chain.doFilter(request, response);

    } finally {
      HttpStatus status = HttpStatus.valueOf(response.getStatus());
      log.info(
          "{} {}, in {}ms",
          status.value(),
          status.getReasonPhrase(),
          System.currentTimeMillis() - start);
    }
  }
 /**
  * API for this method is .../rest/premium_package_properties This method recieves JSON object,
  * and put it in the base. Example for JSON that you need to send some of this attributes not to
  * be default values: <br>
  * {<br>
  * "googlePlayStoreId": null,<br>
  * "itunesStoreId": null,<br>
  * "amazonStoreId": null,<br>
  * "forNonPayingUsers": 0, <br>
  * "redirectPositionTop": null,<br>
  * "redirectPositionLeft": null, <br>
  * "redirectImageUrl": "", "charityDonation": null, <br>
  * "charityDescription": "",<br>
  * "showUntil": null,<br>
  * "maxPurchasesPerUser": null,<br>
  * "idPremiumPackageUpgrade": null, <br>
  * "idFavoriteClub": null,<br>
  * "highlightImageUrl": "",<br>
  * "showOnlySpecial": 0,<br>
  * "imageUrlSpecial": "",<br>
  * "forPayingUsers": 0,<br>
  * "showFrom": null,<br>
  * "updateTimestamp": null,<br>
  * "redirectUrl": "", <br>
  * }
  *
  * @param token is a header parameter for checking permission
  * @param request
  * @param premiumPackageProperties
  * @return Response with status CREATED (201)
  * @throws InputValidationException Example for this exception: <br>
  *     {<br>
  *     "errorMessage": "Validation failed",<br>
  *     "errorCode": 400<br>
  *     }
  */
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 public Response insertPremiumAction(
     @HeaderParam("authorization") String token,
     @Context HttpServletRequest request,
     PremiumPackageProperties premiumPackageProperties) {
   EntityManager em = helper.getEntityManager();
   CmsActionHistory history =
       helper.checkUserAndPrivileges(
           em,
           TableConstants.SHOP,
           MethodConstants.ADD,
           token,
           request.getRequestURL().toString()
               + (request.getQueryString() != null ? "?" + request.getQueryString() : ""),
           premiumPackageProperties);
   premiumPackageProperties.setCreateDate(new Date());
   if (validator.checkLenght(premiumPackageProperties.getCharityDescription(), 255, true)
       && someAttributeIsNotNull(premiumPackageProperties)) {
     premiumPackageProperties.setCreateDate(new Date());
     helper.persistObject(em, premiumPackageProperties);
     Response response = Response.status(Response.Status.CREATED).build();
     helper.setResponseToHistory(history, response, em);
     return response;
   } else {
     helper.setResponseToHistory(history, new InputValidationException("Validation failed"), em);
     throw new InputValidationException("Validation failed");
   }
 }
Ejemplo n.º 4
0
 /**
  * Utility method used when redirecting to a login page.
  *
  * @param request The servlet request object.
  * @param pageInfo The current WikiPageInfo object, which contains information needed for
  *     rendering the final JSP page.
  * @param topic The topic to be redirected to. Valid examples are "Special:Admin",
  *     "StartingPoints", etc.
  * @param messageObject A WikiMessage object to be displayed on the login page.
  * @return Returns a ModelAndView object corresponding to the login page display.
  * @throws Exception Thrown if any error occurs during processing.
  */
 protected static ModelAndView viewLogin(
     HttpServletRequest request, WikiPageInfo pageInfo, String topic, WikiMessage messageObject)
     throws Exception {
   ModelAndView next = new ModelAndView("wiki");
   pageInfo.reset();
   String virtualWikiName = WikiUtil.getVirtualWikiFromURI(request);
   String target = request.getParameter("target");
   if (!StringUtils.hasText(target)) {
     if (!StringUtils.hasText(topic)) {
       VirtualWiki virtualWiki = WikiBase.getDataHandler().lookupVirtualWiki(virtualWikiName);
       topic = virtualWiki.getDefaultTopicName();
     }
     target = topic;
     if (StringUtils.hasText(request.getQueryString())) {
       target += "?" + request.getQueryString();
     }
   }
   next.addObject("target", target);
   pageInfo.setPageTitle(new WikiMessage("login.title"));
   pageInfo.setContentJsp(JSP_LOGIN);
   pageInfo.setSpecial(true);
   if (messageObject != null) {
     next.addObject("messageObject", messageObject);
   }
   return next;
 }
Ejemplo n.º 5
0
 /**
  * Returns the full URL of the request including the query string.
  *
  * <p>Used as a convenience method for logging purposes.
  *
  * @param request the request object.
  * @return the full URL of the request including the query string.
  */
 protected String getRequestURL(HttpServletRequest request) {
   StringBuffer sb = request.getRequestURL();
   if (request.getQueryString() != null) {
     sb.append("?").append(request.getQueryString());
   }
   return sb.toString();
 }
Ejemplo n.º 6
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
Ejemplo n.º 7
0
 /* 发送trace日志到总线上 */
 private void sendTrace(HttpServletRequest req, TraceContext c, BufferedResponseWrapper res) {
   AccessBean b = new AccessBean();
   b.setStamp(FilterHelpers.getRequestTime(req));
   b.setCost((int) FilterHelpers.getCostTime(req));
   b.setTraceId(c.getTraceId());
   b.setRpcId(c.getParentRpcId());
   b.setClientIp(getRemoteIp(req));
   b.setServerIp(ConfigHelper.getServerInnerIP());
   b.setProfile(ConfigHelper.getProcessInfo().getProfile());
   b.setCode(res.getStatus());
   b.setSize(res.getLength());
   b.setReferer(req.getHeader("Referer"));
   b.setUserAgent(req.getHeader("User-Agent"));
   b.setCookie(req.getHeader("Cookie"));
   b.setUid(FilterHelpers.getUserId(req));
   String url = req.getServerName();
   if (req.getServerPort() != 80) {
     url += ':' + req.getServerPort();
   }
   if (req.getQueryString() != null) {
     url += '?' + req.getQueryString();
   }
   b.setUrl(url);
   Message m = new Message("JinJingAccess", c.getTraceId(), JSON.toJSONBytes(b));
   RocketMqSender.getInstance().asyncSend(m);
 }
  // 请求到达控制器之前
  // object: 下一个节点对象
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
      throws Exception {

    // 设置字符编码
    response.setCharacterEncoding(SystemConstant.CHARSET);
    String uri = request.getRequestURI();

    if (StringUtils.isNotEmpty(request.getQueryString())) { // 查询字符串不为空
      uri.concat("?").concat(request.getQueryString());
    }

    logger.debug("URI: " + uri);

    if (object instanceof HandlerMethod) {
      HandlerMethod handlerMethod = (HandlerMethod) object;
      Method method = handlerMethod.getMethod();

      if (method.isAnnotationPresent(Logined.class)) {

        User loginUser = webCtl.getLoginUser(request);
        if (loginUser == null) { // 未登录
          webCtl.addSession(SessionConstant.REDIRECT_URL, uri, request);
          response.sendRedirect(RouteConstant.USER_LOGIN);
          return false;
        }
      }
    }

    return true;
  }
Ejemplo n.º 9
0
  private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
    if (req.getQueryString() == null) return;

    String[] paramsInQueryString = req.getQueryString().split("&");
    if (paramsInQueryString != null) {
      for (String param : paramsInQueryString) {
        String[] paramTokens = param.split("=");
        if (paramTokens != null && paramTokens.length == 2) {
          String name = param.split("=")[0];
          String value = param.split("=")[1];

          try {
            name = URLDecoder.decode(name, "UTF-8");
          } catch (UnsupportedEncodingException e) {
          }
          try {
            value = URLDecoder.decode(value, "UTF-8");
          } catch (UnsupportedEncodingException e) {
          }
          params.put(name, new String[] {value});
        } else {
          s_logger.debug("Invalid paramemter in URL found. param: " + param);
        }
      }
    }
  }
Ejemplo n.º 10
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    // String baseUrl = "http://linux06.fomfrv.dk:8081/aisview/rest";
    String baseUrl = "http://localhost:8092/aisview/rest";
    String url = baseUrl;
    if (request.getPathInfo() != null) {
      url += request.getPathInfo();
    }
    if (request.getQueryString() != null) {
      url += "?" + request.getQueryString();
    }

    LOG.debug("JSOPN proxy request for service: " + url);

    String output;
    try {
      output = requestUrl(url);
      response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
      output = "{\"error\":true}";
      response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
    out.print(output);
  }
Ejemplo n.º 11
0
  @Override
  public void service(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {
    assert request != null;
    assert response != null;

    // Log the request URI+URL muck
    String uri = request.getRequestURI();
    if (request.getQueryString() != null) {
      uri = String.format("%s?%s", uri, request.getQueryString());
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Processing: {} {} ({}) [{}]",
          $(request.getMethod(), uri, request.getRequestURL(), request.getHeader(HUDSON_HEADER)));
    }

    MDC.put(getClass().getName(), uri);
    try {
      super.service(request, response);
    } finally {
      MDC.remove(getClass().getName());
    }

    // Include the version details of the api + model
    response.addHeader(HUDSON_HEADER, String.format("api=%s", getApiVersion()));
  }
Ejemplo n.º 12
0
 private void redirectDuoAuth(
     Principal principal,
     HttpServletRequest httpServletRequest,
     HttpServletResponse httpServletResponse,
     String contextPath)
     throws java.io.IOException {
   // Redirect to servlet if we can.  If the request is committed,
   // we can't, possibly because there's already a redirection in
   // progress; this is what Seraph's SecurityFilter does.
   if (!httpServletResponse.isCommitted()) {
     String sigRequest = DuoWeb.signRequest(ikey, skey, akey, principal.getName());
     final String originalURL =
         contextPath
             + httpServletRequest.getServletPath()
             + (httpServletRequest.getPathInfo() == null ? "" : httpServletRequest.getPathInfo())
             + (httpServletRequest.getQueryString() == null
                 ? ""
                 : "?" + httpServletRequest.getQueryString());
     String qs;
     String redirectUrl;
     qs = DUO_REQUEST_KEY + "=" + URLEncoder.encode(sigRequest, "UTF-8");
     qs = qs + "&" + DUO_HOST_KEY + "=" + URLEncoder.encode(host, "UTF-8");
     qs = qs + "&" + DUO_ORIGINAL_URL_KEY + "=" + URLEncoder.encode(originalURL, "UTF-8");
     redirectUrl = contextPath + loginUrl + "?" + qs;
     httpServletResponse.sendRedirect(redirectUrl);
   } else {
     log.warn("Could not redirect to Duo auth page.");
   }
 }
Ejemplo n.º 13
0
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   HttpSession session = request.getSession();
   Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
   if (principal != null) {
     return true;
   } else {
     String requestType = request.getHeader("X-Requested-With");
     if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
       response.addHeader("loginStatus", "accessDenied");
       response.sendError(HttpServletResponse.SC_FORBIDDEN);
       return false;
     } else {
       if (request.getMethod().equalsIgnoreCase("GET")) {
         String redirectUrl =
             request.getQueryString() != null
                 ? request.getRequestURI() + "?" + request.getQueryString()
                 : request.getRequestURI();
         response.sendRedirect(
             request.getContextPath()
                 + loginUrl
                 + "?"
                 + REDIRECT_URL_PARAMETER_NAME
                 + "="
                 + URLEncoder.encode(redirectUrl, urlEscapingCharset));
       } else {
         response.sendRedirect(request.getContextPath() + loginUrl);
       }
       return false;
     }
   }
 }
 private String getReferer() {
   if (request.getQueryString() != null) {
     return request.getRequestURL() + "?" + request.getQueryString();
   } else {
     return request.getRequestURL().toString();
   }
 }
Ejemplo n.º 15
0
 /**
  * 返回用户请求的完整URL http://11.11.11.11:8080/xxx/xxx/xx.do?xx=aa
  *
  * @param request
  * @return
  */
 public static String getRequestFullURL(HttpServletRequest request) {
   StringBuilder requestURL = new StringBuilder();
   requestURL.append(request.getRequestURL().toString());
   if (request.getQueryString() != null && !"".equals(request.getQueryString())) {
     requestURL.append("?" + request.getQueryString()); // 路径与参数中由?隔开
   }
   return requestURL.toString();
 }
Ejemplo n.º 16
0
  /**
   * This method trys to build a cache key based on the information given in the request - if the
   * page can't be cached, or caching is not availbale then return null
   *
   * @param request
   * @return
   */
  private String getPageCacheKey(HttpServletRequest request) {
    // no license
    if (LicenseUtil.getLevel() < 100) {
      return null;
    }
    // don't cache posts
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
      return null;
    }
    // nocache passed either as a session var, as a request var or as a
    // request attribute
    if ("no".equals(request.getParameter("dotcache"))
        || "no".equals(request.getAttribute("dotcache"))
        || "no".equals(request.getSession().getAttribute("dotcache"))) {
      return null;
    }

    String idInode = (String) request.getAttribute("idInode");

    User user =
        (com.liferay.portal.model.User)
            request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);

    HTMLPage page = null;
    try {
      page = APILocator.getHTMLPageAPI().loadLivePageById(idInode, user, true);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return null;
    }
    if (page == null || page.getCacheTTL() < 1) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(page.getInode());
    sb.append("_" + page.getModDate().getTime());

    String userId = (user != null) ? user.getUserId() : "PUBLIC";
    sb.append("_" + userId);

    String language =
        (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE);
    sb.append("_" + language);

    String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE);
    if (urlMap != null) {
      sb.append("_" + urlMap);
    }

    if (UtilMethods.isSet(request.getQueryString())) {
      sb.append("_" + request.getQueryString());
    }

    return sb.toString();
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    logger.debug("Request URL: " + request.getRequestURI());
    logger.debug("Request Path Info: " + request.getPathInfo());
    logger.debug("Request Param: " + request.getQueryString());

    RestRequest restRequest = null;
    try {
      String url = request.getPathInfo();
      if (request.getQueryString() != null) url += "?" + request.getQueryString();
      restRequest = new RestRequest(url, HttpMethod.POST.name());
    } catch (ServletException e) {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("Invalid URL!");
      return;
    }

    String serviceId = restRequest.getId();
    String format = restRequest.getFormat();

    for (String s : request.getParameterMap().keySet())
      logger.debug(s + " --- " + request.getParameterMap().get(s).toString());
    logger.debug("Id: " + serviceId);
    logger.debug("Format: " + format);

    // request.setCharacterEncoding(CharEncoding.ISO_8859_1);
    logger.info("Content-Type: " + request.getContentType());

    String formData = null;
    String inputLang = "";
    if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_XML))
      inputLang = SerializationLang.XML;
    if (request.getContentType().startsWith(MimeType.TEXT_XML)) inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_XML))
      inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_N3))
      inputLang = SerializationLang.N3;
    if (request.getContentType().startsWith(MimeType.APPLICATION_FORM_URLENCODED)) {
      inputLang = SerializationLang.N3; // default for html forms
      formData = request.getParameter("rdf");
      logger.debug(formData);
    } else {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("The content type is neither rdf+xml nor rdf+n3");
      return;
    }

    InputStream in = request.getInputStream();

    if (formData != null) {
      in = new ByteArrayInputStream(formData.getBytes());
    }

    new PostRequestManager(serviceId, in, inputLang, format, response).HandleRequest();

    response.flushBuffer();
  }
Ejemplo n.º 18
0
  public static String getFullURL(HttpServletRequest request) {

    StringBuffer url = request.getRequestURL();
    if (request.getQueryString() != null) {
      url.append("?");
      url.append(request.getQueryString());
    }
    return url.toString();
  }
 /**
  * 获取当前请求地址
  *
  * @param request
  * @return
  */
 protected String getCurrentUrl(HttpServletRequest request) {
   String rst = request.getScheme() + "://" + request.getServerName();
   int serverPort = request.getServerPort();
   if (serverPort > 0 && serverPort != 80 && serverPort != 8000 && serverPort != 443)
     rst += ":" + serverPort;
   rst += request.getRequestURI();
   if (StringUtils.isNotBlank(request.getQueryString())) rst += "?" + request.getQueryString();
   return rst;
 }
Ejemplo n.º 20
0
 private String constructFullURI(final HttpServletRequest request) {
   final String pathInfo = request.getPathInfo();
   final String queryStr = request.getQueryString();
   final String queryString =
       (queryStr == null || queryStr.equals(""))
           ? ""
           : String.format("?%s", request.getQueryString());
   return String.format("%s%s", pathInfo, queryString);
 }
Ejemplo n.º 21
0
  @SuppressWarnings("unchecked")
  public Principal processIncomingAuthResult(
      HttpServletRequest request, HttpServletResponse response) throws IOException {
    Principal principal = null;
    HttpSession session = request.getSession(false);
    if (session == null) throw new RuntimeException("wrong lifecycle: session was null");

    // extract the parameters from the authentication response
    // (which comes in as a HTTP request from the OpenID provider)
    ParameterList responseParamList = new ParameterList(request.getParameterMap());
    // retrieve the previously stored discovery information
    DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("discovery");
    if (discovered == null) throw new RuntimeException("discovered information was null");
    // extract the receiving URL from the HTTP request
    StringBuffer receivingURL = request.getRequestURL();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0)
      receivingURL.append("?").append(request.getQueryString());

    // verify the response; ConsumerManager needs to be the same
    // (static) instance used to place the authentication request
    VerificationResult verification;
    try {
      verification =
          openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // examine the verification result and extract the verified identifier
    Identifier identifier = verification.getVerifiedId();

    if (identifier != null) {
      AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

      Map<String, List<String>> attributes = null;
      if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
        FetchResponse fetchResp;
        try {
          fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
        } catch (MessageException e) {
          throw new RuntimeException(e);
        }

        attributes = fetchResp.getAttributes();
      }

      principal =
          createOpenIDPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(), attributes);
      request.getSession().setAttribute("PRINCIPAL", principal);

      if (trace) log.trace("Logged in as:" + principal);
    } else {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    return principal;
  }
Ejemplo n.º 22
0
  private void setOriginalUrl(
      HttpServletRequest request, HttpServletResponse response, VDC currentVDC) {
    String requestURI = request.getRequestURI();
    String originalUrl = requestURI;
    String queryString = null;

    if (currentVDC != null) {
      queryString = "?vdcId=" + currentVDC.getId();
    }

    if (request.getQueryString() != null) {
      if (queryString != null) {
        queryString += "&";
      } else {
        queryString = "?";
      }
      queryString += request.getQueryString();
    }

    Enumeration requestNames = request.getAttributeNames();
    while (requestNames.hasMoreElements()) {

      String requestName = (String) requestNames.nextElement();
      if (requestName.startsWith("userId")) {
        if (queryString != null) {
          queryString += "&";
        } else {
          queryString = "?";
        }
        queryString += requestName + "=" + request.getAttribute(requestName);
      }
    }
    if (queryString != null) {
      originalUrl += queryString;
    }
    if (requestURI.indexOf(".xhtml") > -1
        && requestURI.indexOf(PageDefServiceLocal.LOGIN_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.LOGOUT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.ADD_ACCOUNT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.EDIT_ACCOUNT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.UNAUTHORIZED_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CONTRIBUTOR_REQUEST_ACCOUNT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CONTRIBUTOR_REQUEST_SUCCESS_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CONTRIBUTOR_REQUEST_INFO_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CONTRIBUTOR_REQUEST_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CREATOR_REQUEST_ACCOUNT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CREATOR_REQUEST_SUCCESS_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CREATOR_REQUEST_INFO_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.CREATOR_REQUEST_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.FILE_REQUEST_ACCOUNT_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.FILE_REQUEST_SUCCESS_PAGE) == -1
        && requestURI.indexOf(PageDefServiceLocal.FILE_REQUEST_PAGE) == -1
        && request.getMethod().equals("GET")) {
      request.getSession().setAttribute("ORIGINAL_URL", originalUrl);
    }
  }
Ejemplo n.º 23
0
 /**
  * Safe method for retrieving a parameter from the request without disrupting the reader UNLESS
  * the parameter actually exists in the query string.
  *
  * <p>Note, this does not work for POST Requests for "logoutRequest". It works for all other CAS
  * POST requests because the parameter is ALWAYS in the GET request.
  *
  * <p>If we see the "logoutRequest" parameter we MUST treat it as if calling the standard
  * request.getParameter.
  *
  * @param request the request to check.
  * @param parameter the parameter to look for.
  * @return the value of the parameter.
  */
 public static String safeGetParameter(final HttpServletRequest request, final String parameter) {
   if ("POST".equals(request.getMethod()) && "logoutRequest".equals(parameter)) {
     LOG.debug(
         "safeGetParameter called on a POST HttpServletRequest for LogoutRequest.  Cannot complete check safely.  Reverting to standard behavior for this Parameter");
     return request.getParameter(parameter);
   }
   return request.getQueryString() == null || request.getQueryString().indexOf(parameter) == -1
       ? null
       : request.getParameter(parameter);
 }
 protected String homePageRedirection() {
   if (userview.getParamString("menuId").isEmpty()
       && !userview.getPropertyString("homeMenuId").isEmpty()) {
     return "redirect:"
         + getHomePageLink()
         + (request.getQueryString() == null
             ? ""
             : ("?" + StringUtil.decodeURL(request.getQueryString())));
   }
   return null;
 }
  public ServletRestRequest(HttpServletRequest servletRequest) throws IOException {
    this.servletRequest = servletRequest;
    this.method = Method.valueOf(servletRequest.getMethod());
    this.params = new HashMap<String, String>();

    if (servletRequest.getQueryString() != null) {
      RestUtils.decodeQueryString(servletRequest.getQueryString(), 0, params);
    }

    content = Streams.copyToByteArray(servletRequest.getInputStream());
  }
Ejemplo n.º 26
0
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    if (!(req instanceof HttpServletRequest)) {
      chain.doFilter(req, res);
      return;
    }

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

    // Redirect requests with JSESSIONID in URL to clean version (old links bookmarked/stored by
    // bots)
    // This is ONLY triggered if the request did not also contain a JSESSIONID cookie! Which should
    // be fine for bots...
    if (request.isRequestedSessionIdFromURL()) {
      String url =
          request
              .getRequestURL()
              .append(request.getQueryString() != null ? "?" + request.getQueryString() : "")
              .toString();
      // TODO: The url is clean, at least in Tomcat, which strips out the JSESSIONID path parameter
      // automatically (Jetty does not?!)
      response.setHeader("Location", url);
      response.sendError(HttpServletResponse.SC_MOVED_PERMANENTLY);
      return;
    }

    // Prevent rendering of JSESSIONID in URLs for all outgoing links
    HttpServletResponseWrapper wrappedResponse =
        new HttpServletResponseWrapper(response) {
          @Override
          public String encodeRedirectUrl(String url) {
            return url;
          }

          @Override
          public String encodeRedirectURL(String url) {
            return url;
          }

          @Override
          public String encodeUrl(String url) {
            return url;
          }

          @Override
          public String encodeURL(String url) {
            return url;
          }
        };
    chain.doFilter(req, wrappedResponse);
  }
 protected String loginPageRedirection() {
   boolean isAnonymous = WorkflowUtil.isCurrentUserAnonymous();
   boolean hasCurrentPage = userview.getCurrent() != null;
   if ((!isAuthorized || !hasCurrentPage) && isAnonymous) {
     return "redirect:"
         + getLoginLink()
         + (request.getQueryString() == null
             ? ""
             : ("?" + StringUtil.decodeURL(request.getQueryString())));
   }
   return null;
 }
  public String constructRedirectUrl(HttpServletRequest request) {

    String requestURL = request.getRequestURI().split("/app/")[1].trim();
    String queryString = request.getQueryString() != null ? request.getQueryString() : "";

    if ("".equals(queryString)) {
      return "redirect:/" + requestURL + "?" + DETECT_MOBILE_FORCE_WEB;
    } else if (queryString.indexOf(DETECT_MOBILE_FORCE_WEB) == -1) {
      return "redirect:/" + requestURL + "?" + queryString + "&" + DETECT_MOBILE_FORCE_WEB;
    } else {
      return "";
    }
  }
Ejemplo n.º 29
0
  /**
   * Put the original request URL into the request object as an attribute for later use. This is
   * necessary because forwarding a request removes this information. The attribute is only written
   * if it hasn't been before; thus it can be called after a forward safely.
   *
   * @param request the HTTP request
   */
  public static void storeOriginalURL(HttpServletRequest request) {
    String orig = (String) request.getAttribute("dspace.original.url");

    if (orig == null) {
      String fullURL = request.getRequestURL().toString();

      if (request.getQueryString() != null) {
        fullURL = fullURL + "?" + request.getQueryString();
      }

      request.setAttribute("dspace.original.url", fullURL);
    }
  }
  @Override
  public URI getRequestURI() {
    try {
      String uriAsString = _req.getRequestURI();
      if (_req.getQueryString() != null) {
        uriAsString += "?" + _req.getQueryString();
      }

      return new URI(uriAsString);
    } catch (URISyntaxException ex) {
      throw new RuntimeException(ex);
    }
  }