@RequestMapping(method = RequestMethod.POST, consumes = "application/json; charset=utf-8")
  @PreAuthorize(value = "hasRole('AK_ADMIN')")
  @ResponseStatus(HttpStatus.CREATED)
  public void collectionAdd(
      @Valid @RequestBody UserResource p,
      HttpServletRequest request,
      HttpServletResponse response) {

    User bo = dozerBeanMapper.map(p, User.class);
    bo.setIdUser(null);

    try {
      userRepo.save(bo);
    } catch (DataAccessException e) {
      logger.error("Can't create user into DB", e);
      throw new DefaultSportManagerException(
          new ErrorResource(
              "db error", "Can't create user into DB", HttpStatus.INTERNAL_SERVER_ERROR));
    }

    response.setHeader(
        "Location",
        request
            .getRequestURL()
            .append((request.getRequestURL().toString().endsWith("/") ? "" : "/"))
            .append(bo.getIdUser())
            .toString());
  }
 private String getReferer() {
   if (request.getQueryString() != null) {
     return request.getRequestURL() + "?" + request.getQueryString();
   } else {
     return request.getRequestURL().toString();
   }
 }
Beispiel #3
0
  private static void intro(HttpServletRequest req, Element body) {
    body.add(
        "The xAPS Test Verfication Process is a really simple way of testing your TR-069 device and at ");
    body.add(
        "the same time make sure it is interoperable with xAPS. The tests are taken from PD-128v9, which ");
    body.add(
        "is the test document used at TR-069 plugfests. However, only the most basic tests are part of ");
    body.add(
        "of this process; none of the real-world tests are run, which shows that the emphasis in this ");
    body.add(
        "is to get a decent level of interoperability, not to really test if the device can be used for ");
    body.add(
        "all kinds of business purposes. To get a \"complete\" status you need to sucessfully complete all ");
    body.add("the tests.");
    body.p();

    body.add(
        "<b>How to proceed:</b> Connect your CPE to "
            + req.getRequestURL().substring(0, req.getRequestURL().length() - 5)
            + " ");
    body.add(
        "using the same ACS username as you have entered (or are about to enter) below. The ACS will then ");
    body.add(
        "accept both your ACS username and password and immediately respond with the first test. You then ");
    body.add(
        "decide which tests to run. If you so choose, you can set all tests to be run automatically, to ");
    body.add(
        "quickly go through all tests. Just remember to lower your periodic inform interval. ");
    body.add(
        "If your device is not an IAD, change this setting to either VoIP (ATA) or SetTopBox (STB).");
    body.p();
  }
  /**
   * Performs a number of checks to ensure response saneness according to the rules of RFC2616:
   *
   * <ol>
   *   <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then
   *       it is illegal for the body to contain anything. See
   *       http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
   *   <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED}
   *       then it is illegal for the body to contain anything. See
   *       http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
   * </ol>
   *
   * @param request the client HTTP request
   * @param responseStatus the responseStatus
   * @return true if the response should be 0, even if it is isn't.
   */
  public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {

    // Check for NO_CONTENT
    if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "{} resulted in a {} response. Removing message body in accordance with RFC2616.",
            request.getRequestURL(),
            HttpServletResponse.SC_NO_CONTENT);
      }
      return true;
    }

    // Check for NOT_MODIFIED
    if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "{} resulted in a {} response. Removing message body in accordance with RFC2616.",
            request.getRequestURL(),
            HttpServletResponse.SC_NOT_MODIFIED);
      }
      return true;
    }
    return false;
  }
 private void saveUserAccessLog(
     String errorCode, String errorMessage, String username, Integer userId) {
   String uri = httpServletRequest.getRequestURL().toString();
   System.out.println("uri in common is:---" + uri);
   if (!uri.endsWith("/")) uri += "/";
   // get userid for user
   String token = "43f";
   // save user access log
   UserAccessLog accessLog = new UserAccessLog();
   accessLog.setUserId(userId);
   accessLog.setLoginAccessModeId(FiinfraConstants.LOGIN_ACCESS_MODE_STANDARD);
   accessLog.setEnteredPassword(null);
   accessLog.setLoginSuccessful(0);
   accessLog.setRedirectUrl(httpServletRequest.getRequestURL().toString());
   accessLog.setSessionId(httpServletRequest.getSession().getId());
   accessLog.setSourceIPAddress(httpServletRequest.getRemoteAddr());
   accessLog.setFailureCode(errorCode);
   accessLog.setFailureText(errorMessage);
   accessLog.setSourceSystemId(FiinfraConstants.DIY);
   UriComponentsBuilder uriCB =
       UriComponentsBuilder.fromHttpUrl(SAVE_USER_ACCESS_LOG + username + "/" + token);
   // uriCB.queryParam("buId", LoginUtlility.getBuIdForUrl(uri));
   BaseResponse<Boolean> br = new BaseResponse<Boolean>();
   br =
       restTemplate.postForObject(
           FiinfraUtility.getURLWithParams(uriCB), accessLog, BaseResponse.class);
 }
 private String getFeedbackCategory(HttpServletRequest request) {
   String category = null;
   if (request != null && request.getRequestURL() != null) {
     if (request
         .getRequestURL()
         .toString()
         .contains(CustomProperties.FeedbackCategory.RATING.getFeedbackCategory())) {
       category = CustomProperties.FeedbackCategory.RATING.getFeedbackCategory();
     } else if (request
         .getRequestURL()
         .toString()
         .contains(CustomProperties.FeedbackCategory.REPORT.getFeedbackCategory())) {
       category = CustomProperties.FeedbackCategory.REPORT.getFeedbackCategory();
     } else if (request
         .getRequestURL()
         .toString()
         .contains(CustomProperties.FeedbackCategory.FLAG.getFeedbackCategory())) {
       category = CustomProperties.FeedbackCategory.FLAG.getFeedbackCategory();
     } else if (request
         .getRequestURL()
         .toString()
         .contains(CustomProperties.FeedbackCategory.REACTION.getFeedbackCategory())) {
       category = CustomProperties.FeedbackCategory.REACTION.getFeedbackCategory();
     }
   }
   ServerValidationUtils.rejectIfNull(category, GL0007, " request path ");
   return category;
 }
 private String getSummaryCategory(HttpServletRequest request) {
   String category = null;
   if (request.getRequestURL().toString().contains(RESOURCE)) {
     category = RESOURCE;
   } else if (request.getRequestURL().toString().contains(COLLECTION)) {
     category = COLLECTION;
   }
   return category;
 }
  @ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("loaderror");
    return mav;
  }
Beispiel #9
0
  /**
   * GET request parameters as map.
   *
   * @param request request
   * @param pathVariables path markers that should be identified as extra parameters
   * @return map of parameters (with preserved other)
   */
  public static Map<String, List<String>> getParameters(
      final HttpServletRequest request, final Set<String> pathVariables) {

    final String query = request.getQueryString();
    if (StringUtils.isNotBlank(query)) {
      return getParameters(
          request.getRequestURL().toString().concat("?").concat(query), pathVariables);
    }
    return getParameters(request.getRequestURL().toString(), pathVariables);
  }
Beispiel #10
0
 public static void logRealResponse(
     HttpServletRequest realRequest, HttpServletResponse realResponse, StringBuffer logString) {
   StringBuffer before = new StringBuffer();
   before.append("getRequestURL()  " + realRequest.getRequestURL().toString() + "\n");
   before.append("getQueryString()  " + realRequest.getQueryString() + "\n");
   if (realRequest.getRequestURL().toString().contains(".htm")) {
     log.info("logRealResponse: \n" + before + logString);
   } else {
     log.warning("logRealResponse: \n" + before + logString);
   }
 }
  @ExceptionHandler(value = Exception.class)
  public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

    logger.error("[URL] : {}", req.getRequestURL(), e);

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) throw e;

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
  }
Beispiel #12
0
  @ExceptionHandler(TypeMismatchException.class)
  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  public ModelAndView handleTypeMismatchException(
      HttpServletRequest request, TypeMismatchException ex) {
    logger.error("Requested URL=" + request.getRequestURL());
    logger.error("Exception Raised=" + ex);

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("exception", ex);
    modelAndView.addObject("url", request.getRequestURL());

    modelAndView.setViewName("errorPage");
    return modelAndView;
  }
Beispiel #13
0
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   final int delay =
       req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay"));
   try {
     Thread.sleep(delay);
   } catch (InterruptedException e) {
     // ignore
   }
   final String q = req.getParameter("q") == null ? "" : req.getParameter("q");
   if (q.equals("png")) {
     final ServletOutputStream out = res.getOutputStream();
     res.setContentType("image/png");
     copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out);
   } else {
     final PrintWriter out = res.getWriter();
     switch (q) {
       case "html":
         res.setContentType("text/html");
         out.print("<html><body><ul>");
         for (int i = 0; i < 50; i++) {
           out.println("<li>" + i + "</li>");
         }
         out.print("</ul></body></html>");
         break;
       case "json":
         res.setContentType("application/json");
         final ObjectMapper mapper = new ObjectMapper();
         final Map<String, Object> map = new HashMap<>();
         map.put("method", req.getMethod());
         map.put("url", req.getRequestURL().toString());
         map.put("headers", headers(req));
         map.put("query", query(req));
         mapper.writeValue(out, map);
         break;
       case "error":
         res.sendError(500, "Dummy error message");
         break;
       default:
         out.println(req.getMethod() + " " + req.getRequestURL());
         headers(req, out);
         query(req, out);
         copy(req.getReader(), out);
     }
   }
   res.flushBuffer();
 }
  /** 得到cookie的域名 */
  private static final String getDomainName(HttpServletRequest request) {
    String domainName = null;

    String serverName = request.getRequestURL().toString();
    if (serverName == null || serverName.equals("")) {
      domainName = "";
    } else {
      serverName = serverName.toLowerCase();
      serverName = serverName.substring(7);
      final int end = serverName.indexOf("/");
      serverName = serverName.substring(0, end);
      final String[] domains = serverName.split("\\.");
      int len = domains.length;
      if (len > 3) {
        // www.xxx.com.cn
        domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
      } else if (len <= 3 && len > 1) {
        // xxx.com or xxx.cn
        domainName = "." + domains[len - 2] + "." + domains[len - 1];
      } else {
        domainName = serverName;
      }
    }

    if (domainName != null && domainName.indexOf(":") > 0) {
      String[] ary = domainName.split("\\:");
      domainName = ary[0];
    }
    return domainName;
  }
  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
      throws IOException, ServletException {
    m_logger.info("PublisherFilter doFilter");

    HttpServletRequest httpReq = (HttpServletRequest) req;

    String remoteReq = httpReq.getRequestURL().toString();
    int idx = remoteReq.lastIndexOf('/');
    String res = null;
    try {
      String id = req.getParameter("id");
      if (remoteReq.substring(idx).startsWith("/info")) {
        res = m_helper.getInfo(id);
        m_logger.debug(" Pub id=" + id + " " + res);
        if (res == null) {
          req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e200");
        } else {
          resp.setContentType("text/json");
          PrintWriter pm = resp.getWriter();
          pm.write(res);
          pm.close();
        }
      }
    } catch (PaperMinerException ex) {
      req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e201");
    }

    filterChain.doFilter(req, resp);
    return;
  }
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Subject subject = getSubject(request, response);
    if (subject.getPrincipal() == null) {
      if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
        httpResponse.setStatus(401);
        JsonUtil.toJson(new Jo(Jo.CODE_UNLOGIN, "登录超时,请重新登录"), httpResponse);
      } else {
        if (httpRequest.getRequestURI().indexOf("/admin") >= 0) {
          saveRequestAndRedirectToLogin(request, response);
        } else {
          httpResponse.sendRedirect(
              httpRequest.getContextPath()
                  + "/index/loginredirect?redirect="
                  + httpRequest.getRequestURL());
        }
      }
    } else {
      if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) {
        JsonUtil.toJson(new Jo(Jo.CODE_NOPERMISSION, "未授权的操作"), httpResponse);
      } else {
        String unauthorizedUrl = getUnauthorizedUrl();
        if (StringUtils.isEmpty(unauthorizedUrl)) {
          WebUtils.redirectToSavedRequest(request, response, unauthorizedUrl);
        } else {
          WebUtils.toHttp(response).sendError(401);
        }
      }
    }
    return false;
  }
  /** Builds a location URI from the specified request URL and the created object ID. */
  protected URI _buildResourceLocation(final HttpServletRequest request, final String id) {
    String requestUrl = request.getRequestURL().toString();
    URI uri = new UriTemplate("{requestUrl}/{id}").expand(requestUrl, id);
    //        _LOG_.debug( "Location: " + uri.toASCIIString() );

    return uri;
  }
Beispiel #18
0
  /**
   * Redirects the user to the current url over HTTP
   *
   * @param request a HttpServletRequest
   * @param response a HttpServletResponse
   * @param nonSslPort the port Non-SSL requests should be forwarded to
   * @throws ServletException
   * @throws IOException
   */
  public static void redirectOverNonSSL(
      HttpServletRequest request, HttpServletResponse response, int nonSslPort)
      throws ServletException, IOException {

    StringBuffer url = request.getRequestURL();

    // Make sure we're on http
    if (url.charAt(4) == 's') url.deleteCharAt(4);

    // If there is a non-ssl port, make sure we're on it,
    // otherwise assume we're already on the right port
    if (nonSslPort > 0) {
      int portStart = url.indexOf(":", 8) + 1;
      int portEnd = url.indexOf("/", 8);

      if (portEnd == -1) // If their isn't a trailing slash, then the end is the last char
      portEnd = url.length() - 1;

      if (portStart > 0
          && portStart
              < portEnd) { // If we detected a : before the trailing slash or end of url, delete the
                           // port
        url.delete(portStart, portEnd);
      } else {
        url.insert(portEnd, ':'); // If the url didn't have a port, add in the :
        portStart = portEnd;
      }

      url.insert(portStart, nonSslPort); // Insert the right port where it should be
    }

    LogFactory.getLog(ServletUtils.class).debug("redirectOverSSL sending 301: " + url.toString());
    sendPermanentRedirect(response, url.toString());
  }
 /**
  * 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");
   }
 }
 // reporte
 public String loadURL() {
   try {
     HttpServletRequest request =
         (HttpServletRequest) facesContext.getExternalContext().getRequest();
     String urlPath = request.getRequestURL().toString();
     urlPath =
         urlPath.substring(0, urlPath.length() - request.getRequestURI().length())
             + request.getContextPath()
             + "/";
     String urlPDFreporte =
         urlPath
             + "ReporteFactura?pGestion="
             + gestionLogin.getId()
             + "&pEmpresa="
             + empresaLogin.getId()
             + "&pNumero="
             + numeroFactura;
     urlFactura = urlPDFreporte;
     System.out.println("getURL() -> " + urlPDFreporte);
     return urlPDFreporte;
   } catch (Exception e) {
     System.out.println("getURL error: " + e.getMessage());
     return "error";
   }
 }
  @ExceptionHandler(value = {SolrException.class, SolrServerException.class})
  public void handleException(
      Exception ex, HttpServletRequest request, HttpServletResponse response) throws IOException {

    String msg;

    if (ex instanceof SolrException) {
      msg = ex.getLocalizedMessage();
      // Don't send the request as part of error msg
      int requestStart = msg.indexOf("request:");
      if (requestStart > 0) {
        msg = msg.substring(0, requestStart);
      }
    } else if (ex instanceof SolrServerException) {
      msg = appContext.getMessage("oai.solr.unavailable", null, Locale.getDefault());
    } else {
      msg = ex.getLocalizedMessage();
    }

    if (clientXsltHandler != null) {
      clientXsltHandler.sendErrorXml(response, msg, request.getRequestURL().toString());
      ex.printStackTrace();
    } else {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
    }
  }
Beispiel #22
0
  @RequestMapping
  public @ResponseBody String dispatch(HttpServletRequest request) throws Exception {
    String path = request.getRequestURI();
    if (path.indexOf(request.getContextPath()) > -1) {
      path = path.substring(request.getContextPath().length());
    }
    List<Service> services = serviceRepository.findAll();
    for (Service service : services) {
      if (service.getUrl().matches(path)) {
        System.out.println("MATCH: " + service.getUrl());
        SoapService soap = new SoapService();
        soap.setBody(request.getInputStream());
        System.out.println(soap.dispatch());
      }
    }
    System.out.println("PATH " + request.getServletPath());
    System.out.println("QUERY " + request.getQueryString());
    System.out.println("URL " + request.getRequestURL());

    System.out.println("CONTEXT " + request.getContextPath());
    System.out.println("URI " + request.getRequestURI());

    System.out.println(serviceRepository.count());

    return "RESPONSE: " + request;
  }
 private static String getRequestFullUrl(HttpServletRequest request) {
   StringBuffer requestFullURL = request.getRequestURL();
   String queryString = request.getQueryString();
   return queryString == null
       ? requestFullURL.toString()
       : requestFullURL.append('?').append(queryString).toString();
 }
Beispiel #24
0
  private PutMethod convertHttpServletRequestToPutMethod(String url, HttpServletRequest request) {
    PutMethod method = new PutMethod(url);

    for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
      String headerName = (String) headers.nextElement();
      String headerValue = (String) request.getHeader(headerName);
      method.addRequestHeader(headerName, headerValue);
    }

    method.removeRequestHeader("Host");
    method.addRequestHeader("Host", request.getRequestURL().toString());

    StringBuilder requestBody = new StringBuilder();
    try {
      BufferedReader reader = request.getReader();
      String line;
      while (null != (line = reader.readLine())) {
        requestBody.append(line);
      }
      reader.close();
    } catch (IOException e) {
      requestBody.append("");
    }

    method.setRequestEntity(new StringRequestEntity(requestBody.toString()));

    return method;
  }
 protected String buildCallBackURL(HttpServletRequest request, Integer provider) {
   StringBuffer requestURL = request.getRequestURL();
   String callbackURL = requestURL.toString();
   callbackURL += "callback";
   // System.out.println("callback url: " + callbackURL);
   return callbackURL;
 }
Beispiel #26
0
  @RequestMapping(
      value = {"wx/todo/listByPage"},
      method = RequestMethod.GET)
  public void verifyUrl(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    // 获取url验证参数
    java.util.Map<String, String> reqMap = QiYeUtil.requestServerParam(request);
    System.out.println("request=" + request.getRequestURL());

    PrintWriter out = response.getWriter();
    ApproveAccessSecret accessSecret = new ApproveAccessSecret();
    // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
    String result = null;
    try {
      WXBizMsgCrypt wxcpt =
          new WXBizMsgCrypt(
              accessSecret.getToken(), accessSecret.getEncodingAESKey(), AccessSecret.CORPID);
      result =
          wxcpt.VerifyURL(
              reqMap.get("msg_signature"),
              reqMap.get("timestamp"),
              reqMap.get("nonce"),
              reqMap.get("echostr"));
    } catch (AesException e) {
      e.printStackTrace();
    }
    if (result == null) {
      result = accessSecret.getToken();
    }
    out.print(result);
    out.close();
    out = null;
  }
Beispiel #27
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletRequest r = (HttpServletRequest) req;

    // Some info
    LOG.log(Level.INFO, "URL={0}", r.getRequestURL());
    LOG.log(Level.INFO, "URI={0}", r.getRequestURI());
    LOG.log(Level.INFO, "SERVLET PATH={0}", r.getServletPath());
    LOG.log(Level.INFO, "PATH INFO={0}", r.getPathInfo());
    LOG.log(Level.INFO, "QUERY={0}", r.getQueryString());
    LOG.log(Level.INFO, "--------------------------");

    String uri = r.getRequestURI();
    String path = r.getServletPath();
    try {
      // Pass through resources
      if (resources.matcher(uri).matches()) {
        chain.doFilter(req, res);
      } else if (path.equals("/") || path.equals("/home")) {
        req.getRequestDispatcher(TEMPLATE + "?partial=home").forward(req, res);
      } else {
        chain.doFilter(req, res);
      }
    } catch (IOException | ServletException ex) {
      LOG.log(Level.WARNING, ex.getMessage());
      try {
        req.setAttribute("error", ex.getMessage());
        req.getRequestDispatcher(TEMPLATE + "?partial=error").forward(req, res);
      } catch (ServletException | IOException ex1) {
        LOG.log(Level.SEVERE, ex1.getMessage());
      }
    }
  }
 /**
  * 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();
 }
Beispiel #29
0
 private Callable<Void> createAsyncCheckCallable(final CacheKey cacheKey) {
   final HttpServletRequest originalRequest = Context.get().getRequest();
   LOG.debug(
       "OriginalRequest: url={}, uri={}, servletPath={}",
       originalRequest.getRequestURL(),
       originalRequest.getRequestURI(),
       originalRequest.getServletPath());
   final HttpServletRequest request = new PreserveDetailsRequestWrapper(originalRequest);
   return ContextPropagatingCallable.decorate(
       new Callable<Void>() {
         public Void call() throws Exception {
           final String location =
               ResourceWatcherRequestHandler.createHandlerRequestPath(cacheKey, request);
           try {
             dispatcherLocator.locateExternal(request, location);
             return null;
           } catch (final IOException e) {
             final StringBuffer message =
                 new StringBuffer("Could not check the following cacheKey: " + cacheKey);
             if (e instanceof SocketTimeoutException) {
               message
                   .append(". The invocation of ")
                   .append(location)
                   .append(" timed out. Consider increasing the connectionTimeout configuration.");
               LOG.error(message.toString());
             } else {
               LOG.error(message.toString(), e);
             }
             throw e;
           }
         }
       });
 }
Beispiel #30
0
  public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure {
    KeycloakSecurityContext session =
        (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());

    HttpClient client = new HttpClientBuilder().disableTrustManager().build();
    try {
      HttpGet get =
          new HttpGet(
              AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session)
                  + "/auth/admin/realms/demo/roles");
      get.addHeader("Authorization", "Bearer " + session.getTokenString());
      try {
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != 200) {
          throw new Failure(response.getStatusLine().getStatusCode());
        }
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
          return JsonSerialization.readValue(is, TypedList.class);
        } finally {
          is.close();
        }
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } finally {
      client.getConnectionManager().shutdown();
    }
  }