Example usage for javax.servlet.http HttpServletRequest getContextPath

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

Introduction

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

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:org.abstracthorizon.proximity.webapp.controllers.RepositoryController.java

/**
 * Repository list.//  ww  w .  j  av  a 2 s.c o  m
 * 
 * @param request the request
 * @param response the response
 * 
 * @return the model and view
 * 
 * @throws Exception the exception
 */
public ModelAndView repositoryList(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String requestURI = request.getRequestURI()
            .substring(request.getContextPath().length() + request.getServletPath().length());
    if (requestURI.length() == 0) {
        requestURI = "/";
    }
    logger.debug("Got repository request on URI " + requestURI);
    String orderBy = request.getParameter("orderBy") == null ? "name" : request.getParameter("orderBy");
    String targetRepository = request.getParameter("repositoryId");
    String targetGroup = request.getParameter("repositoryGroupId");

    Item item = null;
    ProximityRequest pRequest = new ProximityRequest();
    pRequest.setPath(requestURI);
    pRequest.setTargetedReposId(targetRepository);
    pRequest.setTargetedReposGroupId(targetGroup);
    pRequest.setGrantee(null);
    pRequest.getAttributes().put(ProximityRequest.REQUEST_REMOTE_ADDRESS, request.getRemoteAddr());

    // issue #42, collect header information
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        pRequest.getAttributes().put("http." + headerName.toLowerCase(), request.getHeader(headerName));
    }

    try {
        logger.debug("Got request for " + targetRepository + " repository on URI: " + requestURI);
        item = proximity.retrieveItem(pRequest);
        logger.debug("Got response " + item.getProperties().getPath());

        if (item.getProperties().isDirectory()) {
            List items = null;
            items = proximity.listItems(pRequest);
            PropertyComparator.sort(items, new MutableSortDefinition(orderBy, true, true));
            Map result = new HashMap();
            result.put("items", items);
            result.put("orderBy", orderBy);
            result.put("requestUri", requestURI);
            result.put("requestPathList", explodeUriToList(requestURI));
            return new ModelAndView("repository/repositoryList", result);
        } else {
            // TODO: check for If-Modified-Since?
            // response.setContentType("application/octet-stream");
            response.setContentType(
                    getWebApplicationContext().getServletContext().getMimeType(item.getProperties().getName()));
            response.setContentLength((int) item.getProperties().getSize());
            response.setDateHeader("Last-Modified", item.getProperties().getLastModified().getTime());
            InputStream is = item.getStream();
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            is.close();
            return null;
        }
    } catch (ItemNotFoundException ex) {
        logger.info("Item not found on URI " + requestURI);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (AccessDeniedException ex) {
        logger.info("Access forbidden to " + requestURI + " for " + request.getRemoteAddr(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
}

From source file:com.sonicle.webtop.core.app.servlet.Login.java

private String getBaseUrl(HttpServletRequest request) {
    StringBuffer url = request.getRequestURL();
    String uri = request.getRequestURI();
    String ctx = request.getContextPath();
    return url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
}

From source file:pivotal.au.se.gemfirexdweb.controller.HomeController.java

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String login(Model model, HttpServletResponse response, HttpServletRequest request, HttpSession session)
        throws Exception {
    logger.debug("Received request to show home page");

    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/* w w w  .j av a2 s  . co  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    // This will resolve to /WEB-INF/jsp/main.jsp
    return "main";
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.LoginServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//  w  ww.ja va 2 s  . co  m
        User user = (User) req.getAttribute("user");
        user.setLastLogin(new Date());
        this.servicesClient.updateUser(user, user.getId());
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    } catch (ClientException e) {
        Status responseStatus = e.getResponseStatus();
        if (responseStatus == Status.FORBIDDEN) {
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            resp.sendError(HttpStatus.SC_FORBIDDEN);
        } else {
            throw new ServletException(e);
        }
    }
}

From source file:cn.im47.cloud.storage.utilities.RangingResourceHttpRequestHandler.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String requestPath = requestURI.substring(contextPath.length());

    //locations are set up for delegation if desired
    /*/*from  ww  w. jav  a2s  .c  o  m*/
    if (!requestPath.startsWith("/media/"))  {
    super.handleRequest(request, response);
    }
    */

    boolean useRanges = false;
    int rangeStart = 0;
    int rangeEnd = 0;

    String rangeHeader = request.getHeader(RANGE);
    if (null != rangeHeader) {
        try {
            if (rangeHeader.startsWith(BYTES_PREFIX)) {
                String range = rangeHeader.substring(BYTES_PREFIX.length());
                int splitIndex = range.indexOf("-");
                String startString = range.substring(0, splitIndex);
                String endString = range.substring(splitIndex + 1);
                rangeStart = Integer.parseInt(startString);
                rangeEnd = Integer.parseInt(endString);
                useRanges = true;
            }
        } catch (Exception e) {
            useRanges = false;
            if (log.isLoggable(Level.FINE)) {
                log.fine("Unable to decode range header " + rangeHeader);
            }
        }
    }

    response.setContentType(context.getServletContext().getMimeType(requestPath));
    response.setHeader("Accept-Ranges", "bytes");

    Resource theResource = context.getResource(requestPath);
    String contentLength = Long.toString(theResource.contentLength());
    InputStream in = context.getResource(requestPath).getInputStream();
    OutputStream out = response.getOutputStream();

    if (useRanges) {
        response.setHeader(CONTENT_RANGE, "bytes " + rangeStart + "-" + rangeEnd + "/" + contentLength);
        response.setContentLength(1 + rangeEnd - rangeStart);
        copyStream(in, out, rangeStart, rangeEnd);
    } else {
        copyStream(in, out);
    }
}

From source file:com.bitium.confluence.saml.SAMLContext.java

private String getDefaultBaseURL(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
            .append(request.getServerPort());
    sb.append(request.getContextPath());
    return sb.toString();
}

From source file:com.glaf.base.modules.sys.springmvc.MyMenuController.java

@RequestMapping(params = "method=jump")
public void jump(HttpServletRequest request, HttpServletResponse response) {
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    if (loginContext == null) {
        try {/*from   www.j  a va2  s.c  o m*/
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            return;
        } catch (IOException ex) {
        }
    }
    String menuId = request.getParameter("menuId");
    if (menuId != null) {
        menuId = RequestUtils.decodeString(menuId);
        logger.debug("->menuId:" + menuId);
    } else {
        menuId = request.getParameter("id");
    }
    if (menuId != null && StringUtils.isNumeric(menuId)) {
        TreeModel treeModel = sysApplicationService.getTreeModelByAppId(Long.parseLong(menuId));
        if (treeModel != null) {
            try {
                String url = treeModel.getUrl();
                if (url != null) {
                    if (!(url.toLowerCase().startsWith("http://")
                            || url.toLowerCase().startsWith("https://"))) {
                        if (url.startsWith("/")) {
                            url = request.getContextPath() + url;
                        } else {
                            url = request.getContextPath() + "/" + url;
                        }
                    }
                    if (url.indexOf("?") != -1) {
                        url = url + "&time=" + System.currentTimeMillis();
                    } else {
                        url = url + "?time=" + System.currentTimeMillis();
                    }
                    response.sendRedirect(url);
                } else {
                    return;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    try {
        request.getRequestDispatcher("/WEB-INF/views/404.jsp").forward(request, response);
    } catch (Exception e) {
    }
}

From source file:se.inera.certificate.proxy.filter.ProxyFilter.java

@Override
public Map<String, String> getHeaders(HttpServletRequest httpServletRequest) {
    Map<String, String> headers = newHashMap();
    headers.put("X-Proxy-Original-Servlet-ContextPath",
            defaultIfEmpty(httpServletRequest.getContextPath(), "/"));
    headers.put("X-Proxy-Original-Url", httpServletRequest.getRequestURL().toString());
    headers.put("X-Proxy-Key", this.proxyKey);
    if (headerProvider != null) {
        headers.putAll(headerProvider.getHeaders(httpServletRequest));
    }//from w w  w.j  av  a 2 s.  c o  m
    return headers;
}

From source file:org.chimi.s4s.controller.FileUploadController.java

private String[] createUrl(UploadResult uploadResult, HttpServletRequest request) {
    String url = request.getRequestURL().toString();
    int hostEndIdx = url.indexOf('/', 7);
    String host = url.substring(0, hostEndIdx);
    String contextPath = request.getContextPath();
    String[] urls = new String[2];
    urls[0] = host + contextPath + "/file/" + uploadResult.getFileId();
    if (uploadResult.isImage()) {
        urls[1] = host + contextPath + "/image/o/" + uploadResult.getFileId();
    }// w  ww  . j  a va  2 s  .com
    return urls;
}

From source file:net.solarnetwork.node.setup.web.NodeAssociationFilter.java

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final String path = request.getPathInfo();
    if (!path.startsWith(NODE_ASSOCIATE_PATH) && identityService.getNodeId() == null) {
        response.sendRedirect(request.getContextPath() + NODE_ASSOCIATE_PATH);
    } else {//w w w. java2s.  com
        chain.doFilter(request, response);
    }
}