Example usage for javax.servlet.http HttpServletRequest getServletPath

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

Introduction

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

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:com.netspective.sparx.util.HttpServletResponseCache.java

public void cacheResponse(long servletLastModf, HttpServletRequest req, ResponseCache res) {
    synchronized (pageCache) {
        String cacheKey = req.getServletPath() + req.getPathInfo() + req.getQueryString();
        pageCache.put(cacheKey, new CacheData(res, servletLastModf, req.getServletPath(), req.getPathInfo(),
                req.getQueryString()));// ww w.  j  a  v a  2s.  co m
    }
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *//*from   ww w  .  j  ava2 s.c  o m*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = requestForwarder.cookieNamePrefix.get() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:org.openmrs.module.uiframework.FragmentActionController.java

@RequestMapping("/action/**")
public String handleUrlStartingWithAction(
        @RequestParam(value = "returnFormat", required = false) String returnFormat,
        @RequestParam(value = "successUrl", required = false) String successUrl,
        @RequestParam(value = "failureUrl", required = false) String failureUrl, HttpServletRequest request,
        Model model, HttpServletResponse response) throws Exception {
    // everything after the contextPath, e.g. "/action/emr/registration/checkin.form"
    String path = request.getServletPath();
    path = path.substring("/action/".length(), path.lastIndexOf("."));
    return handlePath(path, returnFormat, successUrl, failureUrl, request, model, response);
}

From source file:net.shopxx.interceptor.LogInterceptor.java

@SuppressWarnings("unchecked")
@Override//from   w  w w. j  a  va2 s  .c  om
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    //List<LogConfig> logConfigs = logConfigService.getAll();
    //??????
    List<LogConfig> logConfigs = logConfigService.findAll();
    if (logConfigs != null) {
        String path = request.getServletPath();
        for (LogConfig logConfig : logConfigs) {
            if (antPathMatcher.match(logConfig.getUrlPattern(), path)) {
                String username = adminService.getCurrentUsername();
                String operation = logConfig.getOperation();
                String operator = username;
                String content = (String) request.getAttribute(Log.LOG_CONTENT_ATTRIBUTE_NAME);
                String ip = request.getRemoteAddr();
                request.removeAttribute(Log.LOG_CONTENT_ATTRIBUTE_NAME);
                StringBuffer parameter = new StringBuffer();
                Map<String, String[]> parameterMap = request.getParameterMap();
                if (parameterMap != null) {
                    for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                        String parameterName = entry.getKey();
                        if (!ArrayUtils.contains(ignoreParameters, parameterName)) {
                            String[] parameterValues = entry.getValue();
                            if (parameterValues != null) {
                                for (String parameterValue : parameterValues) {
                                    parameter.append(parameterName + " = " + parameterValue + "\n");
                                }
                            }
                        }
                    }
                }
                Log log = new Log();
                log.setOperation(operation);
                log.setOperator(operator);
                log.setContent(content);
                log.setParameter(parameter.toString());
                log.setIp(ip);
                logService.save(log);
                break;
            }
        }
    }
}

From source file:com.netpace.vzdn.webapp.vzdninterceptors.SecurityInterceptor.java

public String intercept(ActionInvocation invocation) throws Exception {

    log.debug("Entering Login Interceptor");

    final Object action = invocation.getAction();
    final ActionContext context = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) context.get(HTTP_RESPONSE);
    HttpSession session = request.getSession();
    VzdnUsers currentUser = (VzdnUsers) session.getAttribute(VzdnConstants.LOGGED_IN_USER);
    String userNameFromCookie = getUserNameFromCookie(request, response);

    if (request.getServletPath().contains("deviceAnyWhere"))
        request.getSession().setAttribute("servletURL", request.getServletPath());
    log.debug("request URI is ===" + request.getServletPath());

    System.out.println("User Name from cookie=" + userNameFromCookie);

    if (null != currentUser) {
        if (!userNameFromCookie.equals(currentUser.getUserName())) {
            if (!(action instanceof LoginMarker))
                return VzdnConstants.RESULT_LOGIN_FIRST;
            else//ww  w  . j av a2  s  .c  o m
                return invocation.invoke();
        } else {
            //Further OpenSSO related check must come here when we 
            //know how to find out if the user has a valid Opensso Session or not.
            //If the user is not logged in from opensso, he must simple get invocation.invoke()
            //otherwise, he must get VzdnConstants.RESULT_LOGIN_FIRST;
            log.debug("Invoking the normal  URL : " + request.getServletPath());
            return invocation.invoke();
        }
    } else if (!(action instanceof LoginMarker))
        return VzdnConstants.RESULT_LOGIN_FIRST;
    else
        return invocation.invoke();

}

From source file:org.semispace.semimeter.controller.CounterController.java

/**
 *
 *//*  w  w  w.  ja v  a2s  . c  om*/
@RequestMapping("/**/array.html")
public String showArray(Model model, HttpServletRequest request, HttpServletResponse response,
        @RequestParam String resolution, @RequestParam Integer numberOfSamples) {
    if (numberOfSamples.intValue() < 1) {
        throw new RuntimeException("numberOfSamples must be larger than 0.");
    }
    if (!isSane(request.getServletPath())) {
        throw new RuntimeException("Disallowed character found in query.");
    }
    String path = trimPath("/array.html", request.getServletPath());
    long endAt = semimeterService.getCurrentEndTime();
    long startAt = semimeterService.calculateStartTimeFromResolution(resolution, endAt);
    JsonResults[] jrs = semimeterService.getArrayCounts(resolution, numberOfSamples, path, endAt, startAt);

    String str = jsonService.createJsonStringFromArray(jrs);
    model.addAttribute("numberOfItems", str);

    return "showcount";
}

From source file:io.seldon.api.interceptor.GenericScopedInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    Date start = (Date) request.getAttribute(START_TIME);
    final HttpSession session = request.getSession();
    final ConsumerBean consumerBean = (ConsumerBean) session.getAttribute("consumer");
    String apiKey = request.getServletPath().replaceAll("/", "\\."); //Asumes no user/item ids in path!!!!
    ApiLogger.log(apiKey, start, request, consumerBean);
    super.postHandle(request, response, handler, modelAndView);
}

From source file:net.hedtech.banner.filters.ZKPageFilter2.java

private String extractRequestPath(HttpServletRequest request) {
    String servletPath = request.getServletPath();
    String pathInfo = request.getPathInfo();
    String query = request.getQueryString();
    return (servletPath == null ? "" : servletPath) + (pathInfo == null ? "" : pathInfo)
            + (query == null ? "" : ("?" + query));
}

From source file:it.attocchi.web.filters.NtmlFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    logger.debug("Filtro Ntlm");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpSession session = httpRequest.getSession();

    String requestPath = httpRequest.getServletPath();
    logger.debug("requestPath " + requestPath);

    String user_agent = null;//from w w  w.jav a 2s  .c  om
    String auth = null;

    String workstation = null;
    String domain = null;
    String username = null;

    try {
        /*
         * Operatore loggato? SI: prosegue con il flusso normalmente; NO:
         * tentativo di accesso con utente Windows e poi, se fallisce,
         * redirect alla pagina di autenticazione;
         */
        if ((requestPath != null && requestPath.endsWith("index.jspx"))
                || (requestPath != null && requestPath.endsWith("status.jspx"))
                || requestPath != null && requestPath.endsWith("logout.jspx")
                || requestPath != null && requestPath.endsWith("authenticate.jspx")) {
            logger.debug("Richiesta una pagina fra quelle speciali, esco dal filtro");
            // chain.doFilter(request, response);
            // return;
        } else {

            /* COMMENTATO per problemi POST JSF */
            // // <editor-fold defaultstate="collapsed"
            // desc="DETERMINAZIONE UTENTE WINDOWS">

            /*
             * La tecnica utilizzata (settaggio header) per la
             * determinazione dell'utente Windows  funzionante
             * esclusivamente con browser Microsoft Internet Explorer. Se
             * altro browser salta questo step
             */
            user_agent = httpRequest.getHeader("user-agent");
            // if ((user_agent != null) && (user_agent.indexOf("MSIE") >
            // -1)) {
            if ((user_agent != null)) {
                logger.debug("USER-AGENT: " + user_agent);

                auth = httpRequest.getHeader("Authorization");
                if (auth == null) {
                    logger.debug("STEP1: SC_UNAUTHORIZED");

                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.setHeader("WWW-Authenticate", "NTLM");
                    httpResponse.flushBuffer();
                    return;
                }

                if (auth.startsWith("NTLM ")) {
                    logger.debug("STEP2: NTLM");

                    byte[] msg = org.apache.commons.codec.binary.Base64.decodeBase64(auth.substring(5));
                    // byte[] msg = new
                    // sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
                    int off = 0, length, offset;
                    if (msg[8] == 1) {
                        logger.debug("STEP2a: NTLM");

                        byte z = 0;
                        byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S',
                                (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1,
                                (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z,
                                z, z };
                        // httpResponse.setHeader("WWW-Authenticate",
                        // "NTLM " + new
                        // sun.misc.BASE64Encoder().encodeBuffer(msg1));
                        httpResponse.setHeader("WWW-Authenticate", "NTLM " + Base64.encodeBase64String(msg1));
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                        return;

                    } else if (msg[8] == 3) {
                        logger.debug("STEP2b: read data");

                        off = 30;
                        length = msg[off + 17] * 256 + msg[off + 16];
                        offset = msg[off + 19] * 256 + msg[off + 18];
                        workstation = new String(msg, offset, length);

                        length = msg[off + 1] * 256 + msg[off];
                        offset = msg[off + 3] * 256 + msg[off + 2];
                        domain = new String(msg, offset, length);

                        length = msg[off + 9] * 256 + msg[off + 8];
                        offset = msg[off + 11] * 256 + msg[off + 10];
                        username = new String(msg, offset, length);

                        char a = 0;
                        char b = 32;
                        // logger.debug("Username:" +
                        // username.trim().replace(a, b).replaceAll("",
                        // ""));
                        username = username.trim().replace(a, b).replaceAll(" ", "");
                        workstation = workstation.trim().replace(a, b).replaceAll(" ", "");
                        domain = domain.trim().replace(a, b).replaceAll(" ", "");

                        logger.debug("Username: " + username);
                        logger.debug("RemoteHost: " + workstation);
                        logger.debug("Domain: " + domain);

                        chain.doFilter(request, response);
                    }
                }
            } // if IE
              // </editor-fold>

            /*
             * Mirco 30/09/10: Autentico solo con il nome utente senza il
             * prefisso DOMINIO Questo mi e' utile per i nomi importati da
             * LDAP che hanno specificato solo il nome dell'account
             */
            String winUser = username; // domain + "\\" + username;
            try {
                if (winUser != null) {
                    // utenteDaLoggare =
                    // UtentiDAO.getUtenteByWindowsLogin(winUser);
                }
            } catch (Exception e) {
            }

        }
    } catch (RuntimeException e) {
        logger.error("Errore nel Filtro Autenticazione");
        logger.error(e);
        chain.doFilter(request, response);
    } finally {

    }

    logger.debug("Fine Filtro Ntlm");
}