Example usage for javax.servlet.http HttpServletRequest getRequestURI

List of usage examples for javax.servlet.http HttpServletRequest getRequestURI

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestURI.

Prototype

public String getRequestURI();

Source Link

Document

Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.

Usage

From source file:com.dianping.cache.servlet.RestCacheManagementServlet.java

/**
 * Get building message parameters, and then send this message to JMS
 * server./*  ww  w.  j a v a  2 s.  com*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    try {
        String uri = req.getRequestURI();
        if (StringUtils.isBlank(uri)) {
            out.println("Uri can not be null or empty.");
        }
        String action = uri.substring(uri.lastIndexOf("/") + 1);
        if (action.indexOf("?") != -1) {
            action = action.substring(0, action.indexOf("?"));
        }
        logger.info("uri:" + uri + ", action:" + action);
        if (!REQ_CLEAR_BY_CATEGORY.equalsIgnoreCase(action) && !REQ_CLEAR_BY_KEY.equalsIgnoreCase(action)
                && !REQ_INC_CATEGORY_VERSION.equalsIgnoreCase(action)
                && !REQ_PUSH_CATEGORY_CONFIG.equalsIgnoreCase(action)) {
            out.println("Invalid uri:" + uri
                    + "(Use clearCacheByCategory, clearCacheByKey, incCacheCategoryVersion or pushCacheCategoryConfig)");
        }

        ContextUtils.putLocalContext("CLIENT_IP", IPUtils.getUserIP(req));
        if (REQ_CLEAR_BY_CATEGORY.equalsIgnoreCase(action)) {
            cacheManageService.clearByCategory(req.getParameter(PARAM_CATEGORY), req.getParameter(PARAM_IPS));
        } else if (REQ_CLEAR_BY_KEY.equalsIgnoreCase(action)) {
            cacheManageService.clearByKey(req.getParameter(PARAM_CACHETYPE), req.getParameter(PARAM_KEY));
        } else if (REQ_INC_CATEGORY_VERSION.equalsIgnoreCase(action)) {
            cacheManageService.incVersion(req.getParameter(PARAM_CATEGORY));
        } else {
            cacheManageService.pushCategoryConfig(req.getParameter(PARAM_CATEGORY),
                    req.getParameter(PARAM_IPS));
        }

        out.println("OK");
    } catch (RuntimeException e) {
        out.println("ERROR: " + e.getMessage());
    } finally {
        out.close();
    }
}

From source file:com.google.gwt.site.webapp.server.resources.ContentServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String fullPath = normalizePath(req.getRequestURI());

    Entity e = getResourceByKey(fullPath);

    if (e == null) {
        // temporary try to find the resource with .html appended
        // due to redirects from developers.google.com
        if (!fullPath.endsWith("/")) {
            fullPath = fullPath + ".html";
            e = getResourceByKey(fullPath);
            if (e != null) {
                // redirect so we use correct urls!
                resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                resp.setHeader("Location", "/" + fullPath);
                return;
            }//from   w  w w .  ja  v  a2  s . co m
        }
        resp.sendError(404);
        return;
    }
    String html = ((Text) e.getProperty("html")).getValue();

    setContentTypeByFileEnding(resp, fullPath);

    if (isBinaryFile(fullPath)) {
        byte[] decodeBase64 = org.apache.commons.codec.binary.Base64.decodeBase64(html.getBytes("UTF-8"));
        resp.getOutputStream().write(decodeBase64);
    } else {
        resp.getWriter().write(html);
    }
}

From source file:com.lvlstudios.gtmessage.server.RegisterServlet.java

/**
 * For debug - and possibly show the info, allow device selection.
 *///from   w w  w  .  ja v a 2  s  .c  o m
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.info("doGet " + req.getRequestURI());
    RequestInfo reqInfo = RequestInfo.processRequest(req, resp, getServletContext());
    if (reqInfo == null) {
        return;
    }

    resp.setContentType("application/json");
    JSONObject regs = new JSONObject();
    try {
        regs.put("user", reqInfo.userName);

        JSONArray devices = new JSONArray();
        for (DeviceInfo di : reqInfo.devices) {
            JSONObject dijson = new JSONObject();
            dijson.put("key", di.getKey().toString());
            dijson.put("name", di.getName());
            dijson.put("type", di.getType());
            dijson.put("regid", di.getDeviceRegistrationID());
            dijson.put("ts", di.getRegistrationTimestamp());
            devices.put(dijson);
        }
        regs.put("devices", devices);

        PrintWriter out = resp.getWriter();
        regs.write(out);
    } catch (JSONException e) {
        throw new IOException(e);
    }

}

From source file:com.meltmedia.cadmium.servlets.RedirectFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    Redirect redir = null;/*from  w w w . j  a v  a 2 s. c  o  m*/
    try {
        if (redirect != null && req instanceof HttpServletRequest && resp instanceof HttpServletResponse) {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            String path = request.getRequestURI();
            String queryString = request.getQueryString();
            log.trace("Checking for existing redirect [{}?{}]", path, queryString);
            redir = redirect.requestMatches(path, queryString);
            if (redir != null) {
                String redirectTo = redir.getUrlSubstituted();
                if (StringUtils.isNotBlank(queryString) && !redirectTo.contains("?")) {

                    redirectTo += "?" + queryString;
                    log.debug("adding query string to redirect path: {}", redirectTo);
                }
                response.setHeader("Location", redirectTo);
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                log.debug("Location response header: {}", redirectTo);
                return;
            }
        } else {
            log.trace("Redirect and/or req and resp are not http");
        }
        try {
            chain.doFilter(req, resp);
        } catch (IOException ioe) {
            log.trace("Failed down stream from redirect filter.", ioe);
            throw ioe;
        } catch (ServletException se) {
            log.trace("Failed down stream from redirect filter.", se);
            throw se;
        } catch (Throwable t) {
            StringWriter str = new StringWriter();
            t.printStackTrace(new PrintWriter(str));
            log.trace("Failed down stream from redirect filter: " + str.toString(), t);
            ServletException se = new ServletException(t);
            throw se;

        }
    } catch (Throwable t) {
        StringWriter str = new StringWriter();
        t.printStackTrace(new PrintWriter(str));
        log.debug("Failed in redirect filter: " + str.toString(), t);
        ServletException se = new ServletException(t);
        throw se;
    }
}

From source file:foam.nanos.blob.HttpBlobService.java

protected void download(X x) {
    OutputStream os = null;/*from   w  w w . j av  a2  s  .c om*/
    HttpServletRequest req = x.get(HttpServletRequest.class);
    HttpServletResponse resp = x.get(HttpServletResponse.class);

    try {
        String path = req.getRequestURI();
        String id = path.replaceFirst("/service/" + nspec_.getName() + "/", "");

        Blob blob = getDelegate().find(id);
        if (blob == null) {
            resp.setStatus(resp.SC_NOT_FOUND);
            return;
        }

        long size = blob.getSize();
        resp.setStatus(resp.SC_OK);
        if (blob instanceof FileBlob) {
            File file = ((FileBlob) blob).getFile();
            resp.setContentType(Files.probeContentType(Paths.get(file.toURI())));
        } else {
            resp.setContentType("application/octet-stream");
        }
        resp.setHeader("Content-Length", Long.toString(size, 10));
        resp.setHeader("ETag", id);
        resp.setHeader("Cache-Control", "public");

        os = resp.getOutputStream();
        blob.read(os, 0, size);
        os.close();
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:it.geosolutions.geostore.services.rest.security.RestAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    URI url = null;/*  w ww  .  j  a  v  a  2  s .c o m*/
    try {
        url = new URI(request.getRequestURI());
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        LOGGER.error("Invalid URI:" + request.getRequestURI());
        super.commence(request, response, authException);
        return;
    }
    if (url == null) {
        super.commence(request, response, authException);
        return;
    }
    if (url.getPath().contains(LOGIN_PATH)) {
        response.setHeader("WWW-Authenticate", "FormBased");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        super.commence(request, response, authException);

    }

}

From source file:com.hp.autonomy.frontend.find.core.web.ControllerUtilsImpl.java

private String getBaseUrl(final HttpServletRequest request) {
    final String originalUri = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    final String requestUri = originalUri != null ? originalUri : request.getRequestURI();
    final String path = requestUri.replaceFirst(request.getContextPath(), "");
    final int depth = StringUtils.countMatches(path, "/") - 1;

    return depth <= 0 ? "." : StringUtils.repeat("../", depth);
}

From source file:com.meltmedia.cadmium.servlets.ErrorPageFilterSelectionTest.java

/**
 * Calls doFilter on the ErrorPageFilter, capturing the output.  The output is compared to the expected output.
 * //from w w  w .jav  a2  s.c o  m
 * @throws IOException if there is an error in the test.
 * @throws ServletException if there is an error in the test.
 */
@Test
public void testFilterChainError() throws IOException, ServletException {
    final ByteArrayOutputStream resultWriter = new ByteArrayOutputStream();

    // Return the result writer for output.
    HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int i) throws IOException {
            resultWriter.write(i);
        }
    });
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn(pathInfo);
    // act
    filter.doFilter(request, response, chain);

    // assert
    assertEquals("The wrong error content was returned.", expectedContent, resultWriter.toString());
}

From source file:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho//from   www. j av a 2 s  .c o  m
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}