Example usage for javax.servlet.http HttpServletRequest getPathInfo

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

Introduction

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

Prototype

public String getPathInfo();

Source Link

Document

Returns any extra path information associated with the URL the client sent when it made this request.

Usage

From source file:com.cyclopsgroup.waterview.servlet.ServletRuntimeData.java

/**
 * Default constructor of default web runtime
 *
 * @param request Http request object//from  w  ww .  ja  v  a 2s .  c o m
 * @param response Http response object
 * @param context Http servlet context
 * @param fileUpload File upload component
 * @param services ServiceManager object
 * @param applicationBase application base url
 * @throws Exception Throw it out
 */
ServletRuntimeData(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        FileUpload fileUpload, ServiceManager services, String applicationBase) throws Exception {
    this.response = response;
    this.context = context;

    setQueryString(request.getQueryString());
    setRefererUrl(request.getHeader("referer"));

    //Session Context
    setSessionContext(new HttpSessionContext(request.getSession()));
    setSessionId(request.getSession().getId());

    setRequestContext(new ServletRequestContext(request));

    //Request path
    String requestPath = request.getPathInfo();
    setRequestPath(requestPath == null ? StringUtils.EMPTY : requestPath);

    //Output
    OutputStream outputStream = response.getOutputStream();
    setOutputStream(outputStream);

    InterpolationFilterWriter filterWriter = new InterpolationFilterWriter(new OutputStreamWriter(outputStream),
            '%') {
        /**
         * Overwrite or implement method interpolate()
         *
         * @see com.cyclopsgroup.waterview.utils.InterpolationFilterWriter#interpolate(java.lang.String)
         */
        protected String interpolate(String name) throws Exception {
            I18NService i18n = (I18NService) getServiceManager().lookup(I18NService.ROLE);
            return i18n.translate(name, getLocale());
        }
    };
    setOutput(new PrintWriter(filterWriter));

    //Request value parser
    if (FileUpload.isMultipartContent(request)) {
        setParams(new MultipartServletRequestParameters(request, fileUpload));
    } else {
        setParams(new ServletRequestParameters(request));
    }

    //Service manager
    setServiceManager(services);

    //Application base url
    if (StringUtils.isEmpty(applicationBase)) {
        StringBuffer sb = new StringBuffer(request.getScheme());
        sb.append("://").append(request.getServerName());
        if (request.getServerPort() != 80) {
            sb.append(':').append(request.getServerPort());
        }
        sb.append(request.getContextPath());
        applicationBase = sb.toString();
    }
    setApplicationBaseUrl(applicationBase);

    //Page base url
    setPageBaseUrl(applicationBase + request.getServletPath());
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();
    log.debug(path);/*from   ww  w. j  a  v a 2 s. com*/

    if (path == null) {
        return;
    }
    String[] parts = path.split("/");

    if (path.length() < 1) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }

    // for this validation, the key and secret are passed as POST parameters
    if (StringUtils.equals(parts[1], "validateOAuthConsumer")) {
        validateOAuthConsumer(request, response);
        return;
    }

    HttpSession session = request.getSession();
    String consumerKey = (String) session.getAttribute("consumerKey");
    String consumerSecret = (String) session.getAttribute("consumerSecret");

    if (!checkOAuthConsumer(consumerKey, consumerSecret)) {
        // no valid key in session, no access
        log.error("Request without valid key from " + request.getRemoteAddr());
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to access the servlet!");
        return;
    }

    if (StringUtils.equals(parts[1], "deleteTweet")) {
        deleteTweets(request, response);

    } else if (StringUtils.equals(parts[1], "updateUserStatus")) {
        updateUserStatus(request, response);

    } else if (StringUtils.equals(parts[1], "retweet")) {
        retweet(request, response);

    } else if (StringUtils.equals(parts[1], "verifyCredentials")) {
        verifyCredentials(request, response);

    } else if (StringUtils.equals(parts[1], "getTweets")) {
        getTweets(request, response);

    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request");
        return;
    }
}

From source file:com.jd.survey.web.surveys.SurveyController.java

/**
 * Shows a single Survey /*  w ww .  j  a  v a2s.  co m*/
 * @param surveyId
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "show", produces = "text/html")
public String showSurvey(@PathVariable("id") Long surveyId, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("showSurvey surveyId=" + surveyId + " no pageOrder");
    try {

        //Survey survey =surveyService.Survey_findById(surveyId);
        User user = userService.user_findByLogin(principal.getName());
        SurveyEntry surveyEntry = surveyService.surveyEntry_get(surveyId);

        if (!securityService.userIsAuthorizedToManageSurvey(surveyEntry.getSurveyDefinitionId(), user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyId,
                messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
        uiModel.addAttribute("surveyEntry", surveyEntry);
        uiModel.addAttribute("surveyPages", surveyPages);
        return "surveys/survey";

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:de.micromata.genome.tpsb.httpmockup.MockServletContext.java

public void serveServlet(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, ServletException {
    String uri = req.getRequestURI();
    String localUri = uri;//from  w  w  w . j ava2 s. com
    if (StringUtils.isNotBlank(req.getServletPath()) == true) {
        if (StringUtils.isNotBlank(req.getPathInfo()) == true) {
            localUri = req.getServletPath() + req.getPathInfo();
        } else {
            localUri = req.getServletPath();
        }
    }
    MockServletMapDef map = this.servletsConfig.getServletMappingByPath(localUri);
    if (map == null) {
        map = this.servletsConfig.getServletMappingByPath(uri);
    }
    if (map != null) {
        log.debug("Serve Servlet: " + map.getServletDef().getServlet().getClass().getName());
        map.getServletDef().getServlet().service(req, resp);
    } else {
        log.warn("No servlet found for request: " + req.getRequestURL().toString());
    }
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb./*from   w ww.j  a v  a2  s .c  o  m*/
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

From source file:$.ResourceServlet.java

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing request for resource {}.", resourcePath);
        }//from w  w w  . j  a va2 s .co m

        URL resource = getResourceURL(resourcePath);

        if (resource == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource not found: {}", resourcePath);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");

        URLConnection conn = resource.openConnection();
        long lastModified = conn.getLastModified();

        if (ifModifiedSince >= lastModified) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource: {} Not Modified.", resourcePath);
            }
            response.setStatus(304);
            return;
        }

        int contentLength = conn.getContentLength();

        prepareResponse(response, resource, lastModified, contentLength);

        OutputStream out = selectOutputStream(request, response);

        try {
            InputStream is = conn.getInputStream();
            try {
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = is.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                is.close();
            }
        } finally {
            out.close();
        }

    }

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

@Override
protected void doPut(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    LOGGER.debug("ProxyServlet - PUT");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/*from   w w w  .j  a  v a 2s  .  c  o m*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPut(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }
}

From source file:eionet.web.action.AbstractActionBean.java

/**
 * Returns the real request path./*from w  w w .  j av  a2 s.c  om*/
 *
 * @param request http request
 * @return full urlbinding without decoding
 */
protected String getRequestedPath(HttpServletRequest request) {
    String servletPath, pathInfo;

    // Check to see if the request is processing an include, and pull the path
    // information from the appropriate source.
    servletPath = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH);
    if (servletPath != null) {
        pathInfo = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO);
    } else {
        servletPath = request.getServletPath();
        pathInfo = request.getPathInfo();
    }

    String finalPath = (servletPath != null ? servletPath : "") + (pathInfo != null ? pathInfo : "");
    return finalPath;
}

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

@Override
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - POST");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
        stringBuilder.append(scanner.nextLine());
    }/*from   w  ww.j  a v a2  s  . c o  m*/
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
        servicesClient.proxyPost(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }

}