Java Code Examples for javax.servlet.http.HttpServletRequest#getRequestURI()

The following examples show how to use javax.servlet.http.HttpServletRequest#getRequestURI() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hbase   File: ProfileOutputServlet.java    License: Apache License 2.0 8 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
  throws ServletException, IOException {
  String absoluteDiskPath = getServletContext().getRealPath(req.getPathInfo());
  File requestedFile = new File(absoluteDiskPath);
  // async-profiler version 1.4 writes 'Started [cpu] profiling' to output file when profiler is
  // running which gets replaced by final output. If final output is not ready yet, the file size
  // will be <100 bytes (in all modes).
  if (requestedFile.length() < 100) {
    LOG.info(requestedFile  + " is incomplete. Sending auto-refresh header.");
    String refreshUrl = req.getRequestURI();
    // Rebuild the query string (if we have one)
    if (req.getQueryString() != null) {
      refreshUrl += "?" + sanitize(req.getQueryString());
    }
    ProfileServlet.setResponseHeader(resp);
    resp.setHeader("Refresh", REFRESH_PERIOD + ";" + refreshUrl);
    resp.getWriter().write("This page will be auto-refreshed every " + REFRESH_PERIOD +
      " seconds until the output file is ready. Redirecting to " + refreshUrl);
  } else {
    super.doGet(req, resp);
  }
}
 
Example 2
@Override
public String getValue(String propertyName) {
    if (propertyName.equals(HelloService.class.getName() +  "/mp-rest/url")) {

        try {
            HttpServletRequest request = CDI.current().select(HttpServletRequest.class).get();

            StringBuffer url = request.getRequestURL();
            String uri = request.getRequestURI();

            return url.substring(0, url.length() - uri.length() + request.getContextPath().length()) + "/";
        } catch (Exception e) {
            // Ignore, thrown when the key is requested ahead of a request
        }
    }

    return null;
}
 
Example 3
private boolean isLoginRequest(HttpServletRequest hReq) {
	String uri = hReq.getRequestURI();
	Set<String> loginResources = new HashSet<String>();
	loginResources.add("/auth/");
	loginResources.add("/login/");
	loginResources.add("login.html");
	loginResources.add("/images/q2r.png");
	loginResources.add("/images/youtube.png");
	loginResources.add("/images/github.png");
	loginResources.add("/images/sourceforge.png");
	loginResources.add("/images/wall.jpg");
	loginResources.add("/images/user.png");
	loginResources.add("/CSS/");
	loginResources.add("/JS/");
	loginResources.add("/fonts/");
	for (String resource : loginResources) {
		if(uri.contains(resource)){
			return true;
		}
	}
	return false;
}
 
Example 4
public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
	// SAK-20286 start
	// Get the request
	HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
	String requestURI = req.getRequestURI();
	// Make the attribute name unique to the request 
	String attrName = "sakai.jsf.tool.URL.loopDetect.viewId-" + requestURI;
	// Try to fetch the attribute
	Object attribute = req.getAttribute(attrName);
	// If the attribute is null, this is the first request for this view
	if (attribute == null) {
		req.setAttribute(attrName, "true");
	} else if ("true".equals(attribute)) { // A looping request is detected.
		HttpServletResponse res = (HttpServletResponse) context.getExternalContext().getResponse();
		// Send a 404
		res.sendError(404, "File not found: " + requestURI);
	}
	// SAK-20286 end
	getWrapped().renderView(context, root);
}
 
Example 5
Source Project: tomcatsrc   File: DefaultServlet.java    License: Apache License 2.0 5 votes vote down vote up
private void doDirectoryRedirect(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    StringBuilder location = new StringBuilder(request.getRequestURI());
    location.append('/');
    if (request.getQueryString() != null) {
        location.append('?');
        location.append(request.getQueryString());
    }
    response.sendRedirect(response.encodeRedirectURL(location.toString()));
}
 
Example 6
Source Project: bugu-mongo   File: UploadedFileServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uri = request.getRequestURI();
    //ignore redundant slash
    uri = uri.replaceAll("//", SLASH);
    String servlet = request.getServletPath();
    //skip the servlet name
    int start = uri.indexOf(servlet);
    uri = uri.substring(start + servlet.length());
    //check if the url is valid
    if(uri.length() < 2){
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);  //404
        return;
    }
    
    //get the file name
    int last = uri.lastIndexOf(SLASH);
    String filename = uri.substring(last+1);
    
    HttpFileGetter getter = new HttpFileGetter(request, response);
    getter.setConnection(connection);
    getter.setContentMD5(contentMD5);
    
    int first = uri.indexOf(SLASH);
    if(first != last){
        String sub = uri.substring(first+1, last);
        String[] arr = sub.split(SLASH);
        for(int i=0; i<arr.length; i+=2){
            if(arr[i].equals(BuguFS.BUCKET)){
                getter.setBucket(arr[i+1]);
            }else{
                getter.setAttribute(arr[i], arr[i+1]);
            }
        }
    }
    
    getter.response(filename);
}
 
Example 7
Source Project: maintain   File: CsrfSecurityRequestMatcher.java    License: MIT License 5 votes vote down vote up
public boolean matches(HttpServletRequest request) {
	if (execludeUrls != null && execludeUrls.size() > 0) {
		String servletPath = request.getRequestURI();
		for (String url : execludeUrls) {
			logger.info("path=" + servletPath + "是否包含(" + url + "):" + servletPath.contains(url));
			if (servletPath.contains(url)) {
				return false;
			}
		}
	}
	return !allowedMethods.matcher(request.getMethod()).matches();
}
 
Example 8
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  String path = req.getRequestURI();
  if (path.startsWith("/favicon.ico")) {
    return; // ignore the request for favicon.ico
  }

  // [START example]
  AsyncMemcacheService asyncCache = MemcacheServiceFactory.getAsyncMemcacheService();
  asyncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));
  String key = "count-async";
  byte[] value;
  long count = 1;
  Future<Object> futureValue = asyncCache.get(key); // Read from cache.
  // ... Do other work in parallel to cache retrieval.
  try {
    value = (byte[]) futureValue.get();
    if (value == null) {
      value = BigInteger.valueOf(count).toByteArray();
      asyncCache.put(key, value);
    } else {
      // Increment value
      count = new BigInteger(value).longValue();
      count++;
      value = BigInteger.valueOf(count).toByteArray();
      // Put back in cache
      asyncCache.put(key, value);
    }
  } catch (InterruptedException | ExecutionException e) {
    throw new ServletException("Error when waiting for future value", e);
  }
  // [END example]

  // Output content
  resp.setContentType("text/plain");
  resp.getWriter().print("Value is " + count + "\n");
}
 
Example 9
Source Project: MusicStore   File: CatalogController.java    License: MIT License 5 votes vote down vote up
private String showProduct(HttpServletRequest request,
        HttpServletResponse response) {

   // Retrieve the product code
   String requestURI = request.getRequestURI();
   String[] tokens = requestURI.split("/");
   String productCode = tokens[tokens.length - 1];

   // Retrieve the product from the database and set it as a session attribute
   Product product = ProductDB.selectProduct(productCode);
   HttpSession session = request.getSession();
   session.setAttribute("product", product);

   return "/catalog/single_product.jsp";
}
 
Example 10
Source Project: StatsAgg   File: InfluxdbV2_Write.java    License: Apache License 2.0 5 votes vote down vote up
protected void processPostRequest(HttpServletRequest request, HttpServletResponse response) {
    
    if ((request == null) || (response == null)) {
        return;
    }
    
    long metricsReceivedTimestampInMilliseconds = System.currentTimeMillis();
    
    PrintWriter out = null;
    
    try {
        response.setContentType("text/json"); 
        
        String username = request.getParameter("u");
        String password = request.getParameter("p");
        String httpAuth = request.getHeader("Authorization");
        String retentionPolicy = request.getParameter("rp");
        String consistency = request.getParameter("consistency");
        String timePrecision = request.getParameter("time_precision");

        String json = CharStreams.toString(request.getReader());
        
        String requestUri = request.getRequestURI();
        String database = (requestUri == null) ? null : StringUtils.substringBetween(requestUri, "/db/", "/series");

        parseMetrics(database, json, username, password,  httpAuth, retentionPolicy, consistency, timePrecision, GlobalVariables.influxdbPrefix, metricsReceivedTimestampInMilliseconds);

        out = response.getWriter();
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    finally {            
        if (out != null) {
            out.close();
        }
    }
}
 
Example 11
protected void insertXFrameOptionsHeader(final HttpServletResponse httpServletResponse,
                                         final HttpServletRequest httpServletRequest,
                                         final String xFrameOptions) {
    final String uri = httpServletRequest.getRequestURI();
    httpServletResponse.addHeader("X-Frame-Options", xFrameOptions);
    LOGGER.fine("Adding X-Frame Options " + xFrameOptions + " response headers for [{}]" + uri);
}
 
Example 12
Source Project: plumdo-work   File: RequestLogFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    long beginTime = DateUtils.currentTimeMillis();
    long timeCost;
    String requestUri = request.getRequestURI();
    String method = request.getMethod();
    String ip = request.getRemoteAddr();
    if (isNotJsonContentType(request.getContentType())) {
        filterChain.doFilter(request, response);
        timeCost = DateUtils.getTimeMillisConsume(beginTime);
        log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},[{}]ms", ip, requestUri, method, request.getQueryString(), timeCost);
    } else {
        JsonContentCachingRequestWrapper requestWrapper = new JsonContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        filterChain.doFilter(requestWrapper, responseWrapper);
        timeCost = DateUtils.getTimeMillisConsume(beginTime);
        String requestParam = convertString(requestWrapper.getContentAsByteArray());
        updateResponse(requestUri, responseWrapper);
        if (isNotJsonContentType(responseWrapper.getContentType())) {
            log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},[{}]ms", ip, requestUri, method, requestParam, timeCost);
        } else {
            String result = convertString(responseWrapper.getContentAsByteArray());
            log.debug("ip:{} 调用接口,请求地址为:{}, 方式:{}, 请求参数为:{},返回值是{},[{}]ms", ip, requestUri, method, requestParam, result, timeCost);
        }
    }

}
 
Example 13
@ApiOperation(value = "获取请求信息", notes = "通过重写HttpServletRequest来更改入参")
@ApiImplicitParams({
        //此处只有一个参数,单独使用ApiImplicitParam也可以
        @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long")
})
@RequestMapping(value = CHANGE_USER_URL + "/{userId}", method = RequestMethod.GET)
public PathParam pathPathVariable(HttpServletRequest request, @PathVariable("userId") String userId) {
    return new PathParam("PathVariable", request.getRequestURI(), request.getQueryString(), userId);
}
 
Example 14
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
		throws Exception {
	StopWatch stopWatch = threadLocal.get();
	stopWatch.stop();
	String requestURI = request.getRequestURI();
	logger.info("request:{} comleted use {} ms",requestURI,stopWatch.getTotalTimeMillis());
	threadLocal.remove();
	NDCUtils.clear();
}
 
Example 15
Source Project: nh-micro   File: MicroPageServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String url=request.getRequestURI();
	String context=request.getServletContext().getContextPath();
	int prelen=context.length();
	String busUrl=url.substring(prelen);
	if(prepath!=null && !"".equals(prepath)){
		if(busUrl.startsWith("/"+prepath)){
			busUrl=busUrl.substring(prepath.length()+1);
		}
	}
	String subPath="/WEB-INF"+busUrl;
	request.getRequestDispatcher(subPath).forward(request, response);  

}
 
Example 16
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    Idempotent idempotent = ((HandlerMethod) handler).getMethod().getAnnotation(Idempotent.class);
    if (idempotent == null) {
        return super.preHandle(request, response, handler);
    }
    // 参数设置
    String optType = "[" + request.getMethod() + "]" + Dew.Info.name + "/" + request.getRequestURI();
    String optIdFlag = StringUtils.isEmpty(idempotent.optIdFlag()) ? dewIdempotentConfig.getDefaultOptIdFlag() : idempotent.optIdFlag();
    String optId = request.getHeader(optIdFlag);
    if (StringUtils.isEmpty(optId)) {
        optId = request.getParameter(optIdFlag);
    }
    if (StringUtils.isEmpty(optId)) {
        // optId不存在,表示忽略幂等检查,强制执行
        return super.preHandle(request, response, handler);
    }
    if (!DewIdempotent.existOptTypeInfo(optType)) {
        long expireMs = idempotent.expireMs() == -1 ? dewIdempotentConfig.getDefaultExpireMs() : idempotent.expireMs();
        boolean needConfirm = idempotent.needConfirm();
        StrategyEnum strategy = idempotent.strategy() == StrategyEnum.AUTO ? dewIdempotentConfig.getDefaultStrategy() : idempotent.strategy();
        DewIdempotent.initOptTypeInfo(optType, needConfirm, expireMs, strategy);
    }
    switch (DewIdempotent.process(optType, optId)) {
        case NOT_EXIST:
            return super.preHandle(request, response, handler);
        case UN_CONFIRM:
            ErrorController.error(request, response, 409,
                    "The last operation was still going on, please wait.", IdempotentException.class.getName());
            return false;
        case CONFIRMED:
            ErrorController.error(request, response, 423,
                    "Resources have been processed, can't repeat the request.", IdempotentException.class.getName());
            return false;
        default:
            return false;
    }
}
 
Example 17
Source Project: bumblebee   File: LoginFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    requestURI = requestURI.replaceAll("/+", "/").replaceAll("/+", "/");
    LOG.info("LoginFilter receive request uri : " + requestURI);

    if (requestURI.equals("/")||requestURI.equals("/web/login")||requestURI.equals("/web/doLogin")||requestURI.startsWith("/resources")|| requestURI.startsWith("/terminal/")) {
        filterChain.doFilter(request, response);
        return;
    }
    String path = request.getContextPath();
    this.basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

    HttpSession session = request.getSession();

    BumblebeeUser user=(BumblebeeUser) session.getAttribute("curUser");
    if(null==user){
        java.io.PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<script>");
        out.println("window.open ('"+basePath+"','_top')");
        out.println("</script>");
        out.println("</html>");
    }else{
        filterChain.doFilter(request, response);
        return;
    }


}
 
Example 18
Source Project: DataLink   File: ManagerProxyServlet.java    License: Apache License 2.0 5 votes vote down vote up
protected String rewriteTarget(HttpServletRequest request, String _proxyTo) {
    String path = request.getRequestURI();
    if (!path.startsWith(_prefix))
        return null;

    StringBuilder uri = new StringBuilder(_proxyTo);
    if (_proxyTo.endsWith("/"))
        uri.setLength(uri.length() - 1);
    String rest = path.substring(_prefix.length());
    if (!rest.isEmpty()) {
        if (!rest.startsWith("/"))
            uri.append("/");
        uri.append(rest);
    }

    String query = request.getQueryString();
    if (query != null) {
        // Is there at least one path segment ?
        String separator = "://";
        if (uri.indexOf("/", uri.indexOf(separator) + separator.length()) < 0)
            uri.append("/");
        uri.append("?").append(query);
    }
    URI rewrittenURI = URI.create(uri.toString()).normalize();

    return rewrittenURI.toString();
}
 
Example 19
/**
 * this is the main method of the servlet that will service all get
 * requests.
 *
 * @param request
 *            HttpServletRequest
 * @param responce
 *            HttpServletResponce
 **/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        res.setContentType("text/html");

        // The following 2 lines are the difference between PingServlet and
        // PingServletWriter
        // the latter uses a PrintWriter for output versus a binary output
        // stream.
        ServletOutputStream out = res.getOutputStream();
        // java.io.PrintWriter out = res.getWriter();
        int numReentriesLeft; 
        int sleepTime;
        
        if(req.getParameter("numReentries") != null){
            numReentriesLeft = Integer.parseInt(req.getParameter("numReentries"));
        } else {
            numReentriesLeft = 0;
        }
        
        if(req.getParameter("sleep") != null){
            sleepTime = Integer.parseInt(req.getParameter("sleep"));
        } else {
            sleepTime = 0;
        }
            
        if(numReentriesLeft <= 0) {
            Thread.sleep(sleepTime);
            out.println(numReentriesLeft);
        } else {
            String hostname = req.getServerName();
            int port = req.getServerPort();
            req.getContextPath();
            int saveNumReentriesLeft = numReentriesLeft;
            int nextNumReentriesLeft = numReentriesLeft - 1;
            
            // Recursively call into the same server, decrementing the counter by 1.
            String url = "http://" +  hostname + ":" + port + "/" + req.getRequestURI() + 
                    "?numReentries=" +  nextNumReentriesLeft +
                    "&sleep=" + sleepTime;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            
            //Append the recursion count to the response and return it.
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
     
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            
            Thread.sleep(sleepTime);
            out.println(saveNumReentriesLeft + response.toString());
        }
    } catch (Exception e) {
        //Log.error(e, "PingReentryServlet.doGet(...): general exception caught");
        res.sendError(500, e.toString());

    }
}
 
Example 20
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
	String requestUri = request.getRequestURI();


	ModelAndView result = null;
	//the requestURI must refer to the servelet URI that begins with "/protocol" or "/repositories"
	try {
		//if the requestUri end with "/protocol"
		//it requests the protocol version (GET)
		if (requestUri.endsWith("/" + Protocol.PROTOCOL)) {
			result = (new ProtocolHandler()).serve();
		} else {
			String id = requestUri.substring(requestUri.indexOf("repositories/") + "repositories/".length());
			if (id.contains("/")) {
				id = id.substring(0, id.indexOf("/"));
			}
			final SailRepository repository = (SailRepository) RepositoryManager.getInstance().getRepository(id);
			if (repository == null) {
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				return;
			}
			if (requestUri.endsWith("/" + Protocol.STATEMENTS)) {
				//if the requestUsri ends with "/statements"
				//it requests on repository statements (GET/POST/PUT/DELETE)
				result = (new StatementHandler()).serve(repository, request, response);
			} else if (requestUri.endsWith("/" + Protocol.CONTEXTS)) {
				//if the requestUri ends with "/contexts"
				//it requests context overview (GET)
				result = (new ContextsHandler()).serve(repository, request, response);
			} else if (requestUri.endsWith("/" + Protocol.SIZE)) {
				//if the requestUri ends with "/size"
				//it requests # statements in repository (GET)
				result = (new SizeHandler()).serve(repository, request, response);
			} else if (requestUri.matches("(/|^)(\\w|\\-|\\_)*/repositories/(\\w|\\-|\\_)(\\w|\\-|\\_)*/rdf-graphs(/(\\w|\\-|\\_)(\\w|\\-|\\_)*|$)")) {
				//if the requestUri ends with "/rdf-graphs/*"
				//it requests according to the follows:
				//"/rdf-graphs": named graphs overview (GET)
				//"/ref-graphs/service": SPARQL Graph Store operations on indirectly referenced named graphs in repository (GET/PUT/POST/DELETE)
				//"/ref-graphs/<NAME>": SPARQL Graph Store operationson directly referenced named graphs in repository (GET/PUT/POST/DELETE)
				result = (new GraphHandler()).serve(repository, request, response);
			} else if (requestUri.endsWith("/" + Protocol.NAMESPACES)) {
				//if the requestUri ends with "/namespaces"
				//it requests overview of namespace definitions (GET/DELETE)
				result = (new NamespacesHandler()).serve(repository, request, response);
			} else if (requestUri.matches("(/|^)(\\w|\\-|\\_)*/repositories/(\\w|\\-|\\_)(\\w|\\-|\\_)*/namespaces/(\\w|\\-|\\_)(\\w|\\-|\\_)*")) {
				//if the request matches with "/namespaces/<PREFIX>"
				//it requests namespace-prefix definition (GET/PUT/DELETE)
				result = (new NamespaceHandler()).serve(repository, request, response);
			} else if (requestUri.matches("(/|^)(\\w|\\-|\\_)*/repositories/\\w(\\w|\\-|\\_)*$")) {
				//else it requests the repository information
				result = (new RepositoryHandler()).serve(repository, request, response);
			} else if (requestUri.endsWith("/repositories")) {
				result = (new RepositoryHandler()).serve(repository, request, response);
			}
		}
		result.getView().render(result.getModel(), request, response);
	} catch (Exception e) {
		e.printStackTrace();
	}
}