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.curl.orb.servlet.DefaultInstanceManagementFilter.java

@SuppressWarnings("unchecked")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // accept just HTTP.
    if (!((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)))
        throw new ServletException("The request is not HTTP protocol.");

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    InstanceManagementRequest instanceManagementRequest = null;
    // serialize the request object and set to the attribute
    try {/*from   ww w  .ja v a  2  s . c o  m*/
        if (request.getContentLength() == -1) {
            // forward to requested page.
            request.getRequestDispatcher(httpRequest.getServletPath()).forward(request, response);
            return;
        }
        instanceManagementRequest = (InstanceManagementRequest) serializer
                .deserialize(httpRequest.getInputStream());
        // debug request object (instanceManagementRequest.toString())
        log.debug("Curl ORB Request object [" + instanceManagementRequest + "]");
        httpRequest.setAttribute(InstanceManagementServlet.REQUEST_OBJECT, instanceManagementRequest);
    } catch (SerializerException e) {
        // NOTE: 
        //  Cannot handle the exception when "stream response" mode. 
        //  Clients cannot receive the error.
        setResponse((HttpServletResponse) response,
                new InstanceManagementException("Could not deserialize the object from Curl.", e), null);
        return;
    }

    try {
        // do filters and servlets
        chain.doFilter(httpRequest, response);
        // deserialize the object and return the response
        setResponse((HttpServletResponse) response,
                httpRequest.getAttribute(InstanceManagementServlet.RESPONSE_OBJECT),
                (Map<String, Object>) httpRequest
                        .getAttribute(InstanceManagementServlet.RESPONSE_SUBORDINATE_OBJECT));
    } catch (Exception e) {
        setResponse((HttpServletResponse) response, e, null);
    }
}

From source file:fr.paris.lutece.plugins.rest.service.LuteceJerseySpringServlet.java

/**
 * Checks if the request is authenticated. Sets {@link HttpServletResponse#SC_UNAUTHORIZED} if not,
 * calls {@link ServletContainer#doFilter(HttpServletRequest, HttpServletResponse, FilterChain)} otherwise.
 * @param request the HTTP request/*w  w  w .j av  a  2 s  .c  o  m*/
 * @param response the response
 * @param chain the filter chain
 * @throws IOException exception if I/O error
 * @throws ServletException exception if servlet error
 */
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (checkRequestAuthentification(request)) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("LuteceJerseySpringServlet processing request : " + request.getMethod() + " "
                    + request.getContextPath() + request.getServletPath());
        }
        super.doFilter(request, response, chain);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.jsmartframework.web.manager.ServletControl.java

@Override
@SuppressWarnings("all")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getServletPath();

    // If path is secure, check if user was logged case @AuthBean annotation was provided
    if (checkAuthentication(path, request, response)) {
        return;/*from w w w. ja v a2 s .com*/
    }

    // Check if user is authorized to access the page. Send HTTP 403 response case they did not have
    Integer httpStatus = HANDLER.checkAuthorization(path);
    if (httpStatus != null) {
        LOGGER.log(Level.INFO, "Access not authorized on page [" + path + "]");
        response.sendError(httpStatus);
        return;
    }

    // Check if user is truly valid by carrying CSRF token if implemented
    httpStatus = HANDLER.checkWebSecurityToken(request);
    if (httpStatus != null) {
        LOGGER.log(Level.INFO, "Possibly invalid access via CSRF attack on page [" + path + "]");
        response.sendError(httpStatus);
        return;
    }

    // Decrypt expressions if needed
    Map<String, String> expressions = HANDLER.getRequestExpressions(request);

    // Initiate beans mentioned on jsp page (Case request scope beans)
    try {
        HANDLER.instantiateBeans(path, expressions);
    } catch (Exception ex) {
        LOGGER.log(Level.INFO, "WebBeans on page [" + path + "] could not be instantiated: " + ex.getMessage());
        throw new ServletException(ex);
    }

    // Case user had ordered redirect to specific path in postConstruct method
    String redirectPath = WebContext.getRedirectTo();
    if (redirectPath != null && !redirectPath.equals(path)) {
        sendRedirect(redirectPath, request, response);
        return;
    }

    boolean redirectAjax = false;
    String responsePath = HANDLER.handleRequestExpressions(expressions);

    // Case response was written directly, just return
    if (WebContext.isResponseWritten()) {
        return;
    }

    // Decode the response path case returned from action method
    if (responsePath != null) {
        responsePath = WebUtils.decodePath(responsePath);
    }

    // Case user had ordered redirect to specific path in submitted method
    redirectPath = WebContext.getRedirectTo();
    if (redirectPath != null && !redirectPath.equals(path)) {
        responsePath = redirectPath;
    }

    // Case is Ajax post action and submit method returned a path, let JavaScript redirect page
    if (responsePath != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
        redirectAjax = true;
    }

    if (responsePath == null) {
        responsePath = path;
    } else {

        // Case is Ajax post action, let JavaScript redirect page
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            if (redirectAjax) {
                request.setAttribute(REQUEST_REDIRECT_PATH_AJAX_ATTR,
                        getRedirectPath(responsePath, request, false));
                request.setAttribute(REQUEST_REDIRECT_WINDOW_PATH_AJAX_ATTR, WebContext.isRedirectToWindow());
            }
            responsePath = path;
        }
    }
    sendRedirect(responsePath, request, response);
}

From source file:com.alibaba.cobar.manager.web.PermissionInterceptor.java

private boolean permissioned(HttpServletRequest request) {
    UserDO user = (UserDO) request.getSession().getAttribute("user");
    if (user == null)
        return true;

    String userType = null;/* w w  w .  j a  va  2  s. c  o m*/
    if (user.getUser_role().equals(ConstantDefine.SYSTEM_ADMIN)) {
        userType = ConstantDefine.SYSTEM_ADMIN;
    } else {
        userType = ConstantDefine.CLUSTER_ADMIN;
    }

    HashSet<String> set = (HashSet<String>) nonMatchURIMap.get(userType);
    String url = request.getServletPath().trim();

    return set.contains(url);
}

From source file:com.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java

/**
 * Determine action name by extracting last string and removing extension. (/.../.../Foo.action -> Foo)
 *
 * @param httpServletRequest The HTTP request in play
 * @return the "simple" Action name./*from w w w .j a  v  a  2  s .  c om*/
 */
private String getActionName(HttpServletRequest httpServletRequest) {
    // Get action
    String servletPath = (String) httpServletRequest.getAttribute("javax.servlet.include.servlet_path");
    if (servletPath == null) {
        servletPath = httpServletRequest.getServletPath();
    }

    // Get action name ("Foo.action" -> "Foo" action)
    int beginIdx = servletPath.lastIndexOf("/");
    int endIdx = servletPath.lastIndexOf(ACTION_EXTENSION);
    return servletPath.substring((beginIdx == -1 ? 0 : beginIdx + 1),
            endIdx == -1 ? servletPath.length() : endIdx);
}

From source file:com.yahoo.dba.perf.myperf.springmvc.MetricsController.java

/**
 * URL path pattern: /metrics/{cmd}/{dbgroup}/{dbhost}/[{metrics}/[{start_ts}/][{end_ts}/]]{random}.html
 * cmd://  w  w w. ja  va  2s. co m
 *   get: get one or more metrics for one dbhost. metrics name separated by comma
 * @param req
 * @return
 */
private Map<String, String> parseURL(HttpServletRequest req) {
    Map<String, String> reqParams = new HashMap<String, String>();
    String path = req.getServletPath();
    if (path != null) {
        String[] paths = path.split("/");
        if (paths.length > 2) {
            reqParams.put(Constants.URL_PATH_CMD, paths[2]);
            if (paths.length > 3)
                reqParams.put(Constants.URL_PATH_DBGROUP, paths[3]);
            if (paths.length > 4)
                reqParams.put(Constants.URL_PATH_DBHOST, paths[4]);
            if (paths.length > 5)
                reqParams.put(Constants.URL_PATH_METRICS, paths[5]);
            if (paths.length > 6)
                reqParams.put(Constants.URL_PATH_START_TS, paths[6]);
            if (paths.length > 7)
                reqParams.put(Constants.URL_PATH_END_TS, paths[7]);
        }
    }
    return reqParams;
}

From source file:com.stimulus.archiva.presentation.MessageBean.java

protected void viewMessage(Email email, boolean isOriginalMessage) {
    try {/*from  w w w.ja v a 2  s  .c o  m*/
        this.email = email;
        logger.info("view email {" + email + ", " + getMailArchivaPrincipal() + "}");
        audit.info("view email {" + email + ", " + getMailArchivaPrincipal() + "}");

        //deleteExtractedMessage();
        HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
        String baseURL = hsr.getRequestURL().substring(0,
                hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
        messageExtraction = null; // can take a while to extract message
        lock.lock();
        try {
            messageExtraction = MessageService.extractMessage(email, baseURL, isOriginalMessage);
            extracted.signal();
        } finally {
            lock.unlock();
        }
    } catch (Exception e) {

        logger.error("failed to extract message", e);
    }
}

From source file:com.lube.common.LicenseInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    //        logger.info("=============???==============");
    boolean flag = false;

    //        ILicense license = new UsbKeyLicense();
    //        if (license.verifyLicense()) {
    if (CommonConst.validLicense) {
        logger.debug("???");
        String servletPath = request.getServletPath();
        logger.info("?" + servletPath);
        for (int i = 0; i < paths.length; i++) {
            if (servletPath.equalsIgnoreCase(paths[i])) {
                return true;
            }//w  w w. j  a v  a  2 s  .c om
        }
        User obj = (User) request.getSession().getAttribute(CommonConst.OPERATOR_SESSION_KEY);
        if (null != obj) {

            flag = true;
        } else {
            logger.debug("??");
            //                response.setContentType("application/json;charset=UTF-8");
            //                response.setHeader("Content-Type","application/json;charset=UTF-8");
            //response.setHeader("Transfer-Encoding", "chunked");
            //                Content-Type:application/json;charset=UTF-8

            //                response.setCharacterEncoding("UTF-8");
            //                response.setContentType("text/json");
            //                response.getWriter().write("{\"successful\":false,\"message\":\"??\"}");
            response.sendRedirect("/login.html");
        }
    } else {
        logger.debug("??");
        //            response.sendRedirect("/licenseError.html");
        //            LigerUtils.resultMeaage(false, "?", "90");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setHeader("Transfer-Encoding", "Content-Type:application/json;charset=UTF-8");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        response.getWriter().write("{\"success\":false,\"message\":\""
                + CommonConst.MESSAGE_SYS_LICENSE_VERIFY_FAILD + "\", \"returnCode\":\"90\"}");
    }
    return flag;
}

From source file:io.neba.core.resourcemodels.registration.ModelRegistryConsolePlugin.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String suffix = substringAfter(req.getRequestURI(), req.getServletPath() + "/" + getLabel());
    if (!isBlank(suffix) && suffix.startsWith(API_PATH)) {
        handleApiCall(suffix.substring(API_PATH.length()), req, res);
        return;/*from   w  w w  .j ava 2s  .c  o  m*/
    }
    super.doGet(req, res);
}

From source file:net.maritimecloud.identityregistry.controllers.EntityController.java

/**
 * Updates an entity/* ww  w  . ja  v  a 2  s.  co m*/
 *
 * @return a reply...
 * @throws McBasicRestException
 */
protected ResponseEntity<?> updateEntity(HttpServletRequest request, String orgMrn, String entityMrn, T input)
        throws McBasicRestException {
    if (!entityMrn.equals(input.getMrn())) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being updated belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(entityMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        T entity = this.entityService.getByMrn(entityMrn);
        if (entity == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (entity.getIdOrganization().compareTo(org.getId()) == 0) {
            input.selectiveCopyTo(entity);
            this.entityService.save(entity);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}