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:io.github.alsguo.common.web.filter.BaseFilter.java

/**
 * 1?????//from  ww  w .ja v  a  2  s  .  c o  m
 * 2?????
 */
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String currentURL = httpRequest.getServletPath();

    logger.debug("url filter : current url : [{}]", currentURL);

    if (isBlackURL(currentURL)) {
        chain.doFilter(request, response);
        return;
    }

    if (!isWhiteURL(currentURL)) {
        chain.doFilter(request, response);
        return;
    }
    doFilter(httpRequest, httpResponse, chain);
    return;
}

From source file:io.neba.core.resourcemodels.metadata.ModelMetadataConsolePlugin.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(STATISTICS_API_PATH)) {
        getModelMetadata(suffix.substring(STATISTICS_API_PATH.length()), res);
        return;//from  w  ww.j  a  va 2s. c o  m
    }
    if (!isBlank(suffix) && suffix.startsWith(RESET_API_PATH)) {
        resetStatistics(res);
        return;
    }
    super.doGet(req, res);
}

From source file:eionet.eunis.servlets.StatisticalResultRedirectServlet.java

/**
 *
 * @param req/*from  www. j a  v  a2 s  . co  m*/
 * @param res
 * @throws ServletException
 * @throws IOException
 */
private void handleRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    Chm62edtCountryPersist country = null;

    String servletPath = req.getServletPath();
    if (servletPath == null) {
        return;
    } else if (servletPath.endsWith("sites-statistical-result.jsp")
            || servletPath.endsWith("habitats-country-result.jsp")) {
        String countryNameEn = req.getParameter("country");
        if (StringUtils.isNotBlank(countryNameEn)) {
            country = CountryUtil.findCountry(countryNameEn);
        }
    } else if (servletPath.endsWith("species-country-result.jsp")) {
        int countryId = NumberUtils.toInt(req.getParameter("country"));
        if (countryId > 0) {
            country = CountryUtil.findCountry(countryId);
        } else {
            String countryNameEn = req.getParameter("countryName");
            if (StringUtils.isNotBlank(countryNameEn)) {
                country = CountryUtil.findCountry(countryNameEn);
            }
        }
    }

    if (country == null) {
        res.sendRedirect(req.getContextPath() + "/countries/NOT_FOUND");
    } else {

        String redirUrl = req.getContextPath() + "/countries/" + country.getEunisAreaCode();

        if (servletPath.endsWith("sites-statistical-result.jsp")) {
            boolean showDesignations = BooleanUtils.toBoolean(req.getParameter("showDesignations"));
            if (showDesignations) {
                redirUrl = redirUrl + "/" + CountryFactsheetActionBean.Tab.DESIG_TYPES;
            }
            redirUrl = redirUrl + reconstructQueryString(req.getParameterMap(), "country", "showDesignations");
        } else if (servletPath.endsWith("species-country-result.jsp")) {
            redirUrl = redirUrl + "/" + CountryFactsheetActionBean.Tab.SPECIES;
            redirUrl = redirUrl + reconstructQueryString(req.getParameterMap());
        } else if (servletPath.endsWith("habitats-country-result.jsp")) {
            redirUrl = redirUrl + "/" + CountryFactsheetActionBean.Tab.HABITAT_TYPES;
            redirUrl = redirUrl + reconstructQueryString(req.getParameterMap());
        }
        res.sendRedirect(redirUrl);
    }
}

From source file:com.sfwl.framework.web.casclient.HttpServletRequestWrapperFilter.java

/**
 * Wraps the HttpServletRequest in a wrapper class that delegates
 * <code>request.getRemoteUser</code> to the underlying Assertion object
 * stored in the user session.// w  ww  . j av a  2 s.co  m
 */
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {
    // URL(js+css+img)
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (excepUrlPattern != null && excepUrlPattern.matcher(request.getServletPath()).matches()) {
        filterChain.doFilter(request, response);
        return;
    }

    final AttributePrincipal principal = retrievePrincipalFromSessionOrRequest(servletRequest);

    filterChain.doFilter(new CasHttpServletRequestWrapper((HttpServletRequest) servletRequest, principal),
            servletResponse);
}

From source file:com.nn.cfw.web.security.CustomCsrfPreventionFilter.java

protected String getRequestedPath(HttpServletRequest request) {
    String path = request.getServletPath();
    if (request.getPathInfo() != null) {
        path = path + request.getPathInfo();
    }/*from  w  w w  .  j a  v a 2  s. co m*/
    return path;
}

From source file:com.boundlessgeo.geoserver.AppAuthFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;
    String path = req.getPathInfo();

    if (req.getServletPath().startsWith("/app") && path.startsWith("/api")) {

        if ("POST".equalsIgnoreCase(req.getMethod()) && LOGIN_RE.matcher(path).matches()) {
            // hack: we have to jump through a few hoops to piggy back on the geoserver web auth:
            // 1. we fake the request path to fool the security filter
            // 2. we ignore redirects
            boolean success = runSecurityFilters(new HttpServletRequestWrapper(req) {
                @Override/*from w ww.jav  a 2 s .c  o m*/
                public String getServletPath() {
                    return "";
                }

                @Override
                public String getPathInfo() {
                    return "/j_spring_security_check";
                }
            }, new HttpServletResponseWrapper(res) {
                @Override
                public void sendRedirect(String location) throws IOException {
                }
            }, WEB_LOGIN_CHAIN_NAME);

            if (success) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }

        } else if (LOGOUT_RE.matcher(path).matches()) {
            // invalidate the session if it exists
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        } else {
            // two modes of authentication, basic vs form.
            String chainName = req.getHeader("Authorization") != null ? DEFAULT_CHAIN_NAME : WEB_CHAIN_NAME;
            if (runSecurityFilters(req, res, chainName)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                res.setStatus(401);
            }
        }
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.nedesona.controller.SocialAuthWebController.java

/**
 * Initiates the connection with required provider.It redirects the browser
 * to an appropriate URL which will be used for authentication with the
 * requested provider./*from  w w w. j  a v  a 2  s.c o m*/
 */
@SuppressWarnings("unused")
@RequestMapping(params = "id")
private String connect(@RequestParam("id") final String providerId, final HttpServletRequest request)
        throws Exception {
    LOG.debug("Getting Authentication URL for :" + providerId);
    String callbackURL = baseCallbackUrl + request.getServletPath();
    String url = socialAuthManager.getAuthenticationUrl(providerId, callbackURL);
    if (callbackURL.equals(url)) {
        url = successPageURL;
        socialAuthManager.connect(new HashMap<String, String>());
    }

    socialAuthTemplate.setSocialAuthManager(socialAuthManager);
    return "redirect:" + url;
}

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

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SearchBean searchBean = (SearchBean) form;

    String outputDir = Config.getFileSystem().getViewPath() + File.separatorChar;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String zipFileName = "export-" + sdf.format(new Date()) + ".zip";
    File zipFile = new File(outputDir + zipFileName);

    String agent = request.getHeader("USER-AGENT");
    if (null != agent && -1 != agent.indexOf("MSIE")) {
        String codedfilename = URLEncoder.encode(zipFileName, "UTF8");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        String codedfilename = MimeUtility.encodeText(zipFileName, "UTF8", "B");
        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
    } else {//from  www. j  ava  2 s  .c  om
        response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
    }

    logger.debug("size of searchResult = " + searchBean.getSearchResults().size());
    //MessageBean.viewMessage
    List<File> files = new ArrayList<File>();
    for (SearchResultBean searchResult : searchBean.getSearchResults()) {
        if (searchResult.getSelected()) {
            Email email = MessageService.getMessageByID(searchResult.getVolumeID(), searchResult.getUniqueID(),
                    false);

            HttpServletRequest hsr = ActionContext.getActionContext().getRequest();
            String baseURL = hsr.getRequestURL().substring(0,
                    hsr.getRequestURL().lastIndexOf(hsr.getServletPath()));
            MessageExtraction messageExtraction = MessageService.extractMessage(email, baseURL, true); // can take a while to extract message

            //              MessageBean mbean = new MessageBean();
            //              mbean.setMessageID(searchResult.getUniqueID());
            //              mbean.setVolumeID(searchResult.getVolumeID());
            //              writer.println(searchResult.toString());
            //              writer.println(messageExtraction.getFileName());

            File fileToAdd = new File(outputDir, messageExtraction.getFileName());
            if (!files.contains(fileToAdd)) {
                files.add(fileToAdd);
            }
        }
    }

    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
        byte[] buf = new byte[1024];
        for (File f : files) {
            ZipEntry ze = new ZipEntry(f.getName());
            logger.debug("Adding file " + f.getName());
            zos.putNextEntry(ze);
            InputStream is = new BufferedInputStream(new FileInputStream(f));
            for (;;) {
                int len = is.read(buf);
                if (len < 0)
                    break;
                zos.write(buf, 0, len);
            }
            is.close();
            Config.getFileSystem().getTempFiles().markForDeletion(f);
        }
    } finally {
        zos.close();
    }
    logger.debug("download zipped emails {fileName='" + zipFileName + "'}");

    String contentType = "application/zip";
    Config.getFileSystem().getTempFiles().markForDeletion(zipFile);
    return new FileStreamInfo(contentType, zipFile);
}

From source file:io.neba.core.resourcemodels.metadata.ModelStatisticsConsolePlugin.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(STATISTICS_API_PATH)) {
        setNoCacheHeaders(res);/*  w  ww.j  a  v  a  2s  .  c  o m*/
        getModelMetadata(suffix.substring(STATISTICS_API_PATH.length()), res);
        return;
    }
    if (!isBlank(suffix) && suffix.startsWith(RESET_API_PATH)) {
        setNoCacheHeaders(res);
        resetStatistics(res);
        return;
    }
    super.doGet(req, res);
}

From source file:com.netspective.sparx.value.source.PageIdValueSource.java

/**
 * Gets the navigation page's URL as a Value object. If the navigation tree or the page itself
 * was not found, a GenericValue object with the error message is returned.
 *///from  w ww.ja  v a  2  s . c  o m
public Value getValue(ValueContext vc) {
    NavigationTree navTree = null;
    HttpServletValueContext svc = (HttpServletValueContext) (vc instanceof ConnectionContext
            ? ((ConnectionContext) vc).getDatabaseValueContext()
            : vc);
    HttpServletRequest request = svc.getHttpRequest();
    String contextPath = request.getContextPath();
    String servletPath = request.getServletPath();

    if (treeSource == null || treeSource.length() == 0) {
        final NavigationContext navigationContext = svc.getNavigationContext();
        if (navigationContext != null)
            navTree = navigationContext.getActivePage().getOwner();
        else {
            AuthenticatedUser user = svc.getAuthenticatedUser();
            if (user instanceof NavigationControllerAuthenticatedUser)
                navTree = ((NavigationControllerAuthenticatedUser) user).getUserSpecificNavigationTree(
                        (NavigationControllerServlet) svc.getHttpServlet(), svc.getHttpRequest(),
                        svc.getHttpResponse());
            else
                navTree = svc.getProject().getDefaultNavigationTree();
        }
        if (navTree == null)
            return new GenericValue("No default NavigationTree found");
    } else {
        navTree = navTree = svc.getProject().getNavigationTree(treeSource);
        if (navTree == null)
            return new GenericValue("No navigation tree named '" + treeSource + "' was found");
    }

    if (!pageId.startsWith("/")) {
        // relative page ID
        NavigationPage activePage = svc.getNavigationContext().getActivePage();
        if (activePage != null)
            pageId = activePage.getQualifiedName() + "/" + pageId;
        else {
            log.error("Active page was not found for relative page ID '" + pageId + "'.");
            return new GenericValue("Active page was not found for relative page ID '" + pageId + "'.");
        }
    }
    // find a matching path with respect to the nav id
    NavigationTree.FindResults pathResults = navTree.findPath(pageId);
    NavigationPath path = pathResults.getMatchedPath();
    if (path == null) {
        // a matching path was not found
        log.error("Navigation page ID '" + pageId + "' was not found.");
        return new GenericValue("Navigation page ID '" + pageId + "' was not found.");
    } else {
        String localParams = null;
        if (reqParams != null) {
            // process the request parameters
            localParams = reqParams.getValue(vc).getTextValue();
        }
        return new GenericValue(contextPath + servletPath + path.getQualifiedName()
                + (localParams != null ? "?" + localParams : ""));
    }
}