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:ch.entwine.weblounge.kernel.webconsole.WebConsolePlugin.java

/**
 * {@inheritDoc}//from  w  w  w.  j  a v a2 s .  c  o m
 * 
 * @see org.apache.felix.webconsole.AbstractWebConsolePlugin#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getPathInfo().endsWith("/index.json")) {
        response.setContentType("text/json");
        String json = addSitesData("${" + SITES_DATA_KEY + "}");
        response.getWriter().print(json);
        return;
    } else {
        super.doGet(request, response);
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.FriendServlet.java

private void friendApiConnectionLogic(HttpServletRequest request, HttpServletResponse response, Friend myFriend)
        throws IOException {
    String pathInfo = request.getPathInfo();
    PrintWriter out = response.getWriter();
    JsonObject json;/* w ww  .  ja  v  a2s . c  om*/
    switch (pathInfo) {
    case "/friendCreate":
        String friendInviteEmail = request.getParameter(PARAMETER_ID);
        String friendInstructorEmail = request.getParameter(PARAMETER_INSTRUCTOR_EMAIL);
        String friendInstructorFirstName = request.getParameter(PARAMETER_INSTRUCTOR_FIRST_NAME);
        String friendInstructorLastName = request.getParameter(PARAMETER_INSTRUCTOR_LAST_NAME);
        String friendNotifyInstructor = request.getParameter(PARAMETER_NOTIFY_INSTRUCTOR);
        if (friendInviteEmail == null || friendInstructorEmail == null || friendInstructorFirstName == null
                || friendInstructorLastName == null) {
            response.setStatus(400);
            json = Json.createObjectBuilder().add("message", "requestError")
                    .add("detailedMessage", "request error: required parameters for request not specified")
                    .add("FriendURL", Friend.friendUrl).build();
        } else {
            json = doFriendLogic(myFriend, friendInviteEmail, friendInstructorEmail, friendInstructorFirstName,
                    friendInstructorLastName, friendNotifyInstructor);
        }
        break;
    default:
        response.setStatus(400);
        json = Json.createObjectBuilder().add("message", "request error").build();
        break;
    }
    out.print(json.toString());
    out.flush();
}

From source file:com.seajas.search.attender.controller.FeedController.java

/**
 * Handle the request./*from ww w . j a  v  a2 s  .c o m*/
 * 
 * @param request
 * @param response
 * @param locale
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.GET)
public void handleRequest(final HttpServletRequest request, final HttpServletResponse response,
        final Locale locale) throws Exception {
    String path = request.getPathInfo();

    Integer results = null;
    String feedType = null;

    // The number of results may be optionally provided

    if (!StringUtils.isEmpty(request.getParameter(PARAM_RESULTS)))
        try {
            results = Integer.valueOf(request.getParameter(PARAM_RESULTS));
        } catch (NumberFormatException e) {
            throw new Exception("Invalid result number given");
        }
    if (!StringUtils.isEmpty(request.getParameter(PARAM_TYPE)))
        feedType = request.getParameter(PARAM_TYPE);

    // Reconstruct the URL from the request

    String baseUrl = request.getRequestURL().toString();

    if (!StringUtils.isEmpty(request.getQueryString()))
        baseUrl += "?" + request.getQueryString();

    if (path != null && path.startsWith("/feed"))
        path = path.substring(5);
    if (path != null && path.startsWith("/"))
        path = path.substring(1);

    if (!StringUtils.isEmpty(path)) {
        String[] pathParts = path.split("/");

        // The first part should always indicate the UUID

        String profileUUID = pathParts[0];

        // The second part is optional and defines the notification type

        NotificationType notificationType = pathParts.length > 1
                && pathParts[1].equalsIgnoreCase(NotificationType.Weekly.toString()) ? NotificationType.Weekly
                        : NotificationType.Daily;

        // First retrieve the profile and create the actual feed

        Profile profile = attenderService.getProfileByUUID(profileUUID);

        if (profile == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown feed '" + profileUUID + "'");

            return;
        }

        // Must have at least one confirmed subscriber

        Boolean isConfirmedOnce = false;

        for (ProfileSubscriber subscriber : profile.getSubscribers())
            if (subscriber.getIsConfirmed()) {
                isConfirmedOnce = true;

                break;
            }

        if (!isConfirmedOnce) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "This feed has no confirmed subscribers");

            return;
        }

        SyndFeed result = feedService.createFeed(profile, notificationType, results, baseUrl, locale);

        // Set the feed type, or revert to the default

        if (feedType != null && availableFeedTypes.contains(feedType))
            result.setFeedType(feedType);
        else
            result.setFeedType("rss_2.0");

        // Set the response type and write out the result

        response.setContentType("application/xml; charset=UTF-8");

        SyndFeedOutput output = new SyndFeedOutput();
        output.output(result, response.getWriter());
    } else
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "No feed given");
}

From source file:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);//from   w  w w.j  a v  a  2 s.  com
    } else if (pathInfo == null || pathInfo.length() == 1) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        String referenceId = pathInfo.substring(1);
        boolean pending = Boolean.parseBoolean(request.getParameter("pending"));
        serialize(referenceId, pending, response);
    }
}

From source file:org.lareferencia.xoai.services.impl.xoai.LRRepositoryConfiguration.java

@Override
public String getBaseUrl() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();/*  w w  w.j ava  2  s. com*/
    if (baseUrl == null) {
        baseUrl = request.getRequestURL().toString().replace(request.getPathInfo(), "");
    }
    return baseUrl + request.getPathInfo();
}

From source file:io.liuwei.web.StaticContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ??//ww  w .j a v a 2s.  co m
    String contentPath = request.getPathInfo();
    if (StringUtils.isBlank(contentPath) || "/".equals(contentPath)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "contentPath parameter is required.");
        return;
    }

    // ??.
    ContentInfo contentInfo = getContentInfo(contentPath);
    if (!contentInfo.file.exists()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "file not found.");
        return;
    }

    // ?EtagModifiedSince Header?, ??304,.
    if (!Servlets.checkIfModifiedSince(request, response, contentInfo.lastModified)
            || !Servlets.checkIfNoneMatchEtag(request, response, contentInfo.etag)) {
        return;
    }

    // Etag/
    Servlets.setExpiresHeader(response, Servlets.ONE_YEAR_SECONDS);
    Servlets.setLastModifiedHeader(response, contentInfo.lastModified);
    Servlets.setEtag(response, contentInfo.etag);

    // MIME
    response.setContentType(contentInfo.mimeType);

    // ?Header
    if (request.getParameter("download") != null) {
        Servlets.setFileDownloadHeader(response, contentInfo.fileName);
    }

    // OutputStream
    OutputStream output;
    if (checkAccetptGzip(request) && contentInfo.needGzip) {
        // outputstream, http1.1 trunked??content-length.
        output = buildGzipOutputStream(response);
    } else {
        // outputstream, content-length.
        response.setContentLength(contentInfo.length);
        output = response.getOutputStream();
    }

    // ?,?input file
    FileUtils.copyFile(contentInfo.file, output);
    output.flush();
}

From source file:annis.gui.servlets.ResourceServlet.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream outStream = response.getOutputStream();

    String completePath = request.getPathInfo();

    if (completePath == null) {
        response.sendError(404, "must provide a valid and existing path with a vistype");
        return;/* w ww  . ja  v  a  2 s  .  c  om*/
    }

    // remove trailing /
    completePath = completePath.substring(1);

    String[] pathComponents = completePath.split("/");

    String vistype = pathComponents[0];

    if (pathComponents.length < 2) {
        response.sendError(404, "must provide a valid and existing path");
        return;
    }

    String path = StringUtils.join(Arrays.copyOfRange(pathComponents, 1, pathComponents.length), "/");

    // get the visualizer for this vistype
    ResourcePlugin vis = resourceRegistry.get(vistype);
    if (vis == null) {
        response.sendError(500, "There is no resource with the short name " + vistype);
    } else if (path.endsWith(".class")) {
        response.sendError(403, "illegal class path access");
    } else {
        URL resource = vis.getClass().getResource(path);
        if (resource == null) {
            response.sendError(404, path + " not found");
        } else {
            // check if it is new
            URLConnection resourceConnection = resource.openConnection();
            long resourceLastModified = resourceConnection.getLastModified();
            long requestLastModified = request.getDateHeader("If-Modified-Since");
            if (requestLastModified != -1 && resourceLastModified <= requestLastModified) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.addDateHeader("Last-Modified", resourceLastModified);
                if ("localhost".equals(request.getServerName())) {
                    // does always expire right now
                    response.addDateHeader("Expires", new Date().getTime());
                } else {
                    // expires in one minute per default
                    response.addDateHeader("Expires", new Date().getTime() + 60000);
                }
                // not in cache, stream out
                String mimeType = getServletContext().getMimeType(path);
                response.setContentType(mimeType);
                if (mimeType.startsWith("text/")) {
                    response.setCharacterEncoding("UTF-8");
                }
                OutputStream bufferedOut = new BufferedOutputStream(outStream);
                InputStream resourceInStream = new BufferedInputStream(resource.openStream());

                try {
                    int v = -1;
                    while ((v = resourceInStream.read()) != -1) {
                        bufferedOut.write(v);
                    }
                } finally {
                    resourceInStream.close();
                    bufferedOut.flush();
                    outStream.flush();
                }
            }
        }
    }

}

From source file:com.acmeair.web.RESTCookieSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    try {//  www  .  j  av  a2s .  co m
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();
        // The following code is to ensure that OG is always set on the thread
        try {
            TransactionService txService = getTxService();
            if (txService != null)
                txService.prepareForTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // could do .startsWith for now, but plan to move LOGOUT to its own REST interface eventually
        if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH)) {
            // if logging in, let the request flow
            chain.doFilter(req, resp);
            return;
        }

        Cookie cookies[] = request.getCookies();
        Cookie sessionCookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
                    sessionCookie = c;
                }
                if (sessionCookie != null)
                    break;
            }
            String sessionId = "";
            if (sessionCookie != null) // We need both cookie to work
                sessionId = sessionCookie.getValue().trim();
            else {
                log.info("falling through with a sessionCookie break, but it was null");
            }
            // did this check as the logout currently sets the cookie value to "" instead of aging it out
            // see comment in LogingREST.java
            if (sessionId.equals("")) {
                log.info("sending SC_FORBIDDEN due to empty session cookie");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // Need the URLDecoder so that I can get @ not %40
            ValidateTokenCommand validateCommand = new ValidateTokenCommand(sessionId);
            CustomerSession cs = validateCommand.execute();
            if (cs != null) {
                request.setAttribute(LOGIN_USER, cs.getCustomerid());
                chain.doFilter(req, resp);
                return;
            } else {
                log.info("sending SC_FORBIDDEN due  to validateCommand returning null");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        // if we got here, we didn't detect the session cookie, so we need to return 403
        log.info("sending SC_FORBIDDEN due finding no sessionCookie");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:dinamica.util.matcher.RegexRequestMatcher.java

/**
 * Performs the match of the request URL ({@code servletPath + pathInfo + queryString}
 * ) against the compiled pattern. If the query string is present, a question mark
 * will be prepended./*  www . j  a  v  a 2 s  .  com*/
 *
 * @param request the request to match
 * @return true if the pattern matches the URL, false otherwise.
 */
public boolean matches(HttpServletRequest request) {
    if (httpMethod != null && request.getMethod() != null && httpMethod != valueOf(request.getMethod())) {
        return false;
    }

    String url = request.getServletPath();
    String pathInfo = request.getPathInfo();
    String query = request.getQueryString();

    if (pathInfo != null || query != null) {
        StringBuilder sb = new StringBuilder(url);

        if (pathInfo != null) {
            sb.append(pathInfo);
        }

        if (query != null) {
            sb.append('?').append(query);
        }
        url = sb.toString();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Checking match of request : '" + url + "'; against '" + pattern + "'");
    }

    return pattern.matcher(url).matches();
}

From source file:net.fenyo.mail4hotspot.web.GMailOAuthStep1Servlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {//from w  ww  .j ava 2s .  co m
        if (request.getPathInfo().equals("/step1")) {
            //            final String uuid = request.getParameter("uuid");
            final String nonce = nonce();
            final String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);
            final String base_string = "GET&"
                    + urlEncode("https://www.google.com/accounts/OAuthGetRequestToken") + "&"
                    + urlEncode("oauth_callback=" + urlEncode(base + "oauth/step2")
                            + "&oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                            + "&oauth_version=1.0&scope=" + urlEncode("https://mail.google.com/"));
            log.debug("digestencoded=" + urlEncode(hmac(consumer_secret + "&", base_string)));
            final String url = "https://www.google.com/accounts/OAuthGetRequestToken?oauth_consumer_key=www.vpnoverdns.com&oauth_nonce="
                    + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now
                    + "&oauth_version=1.0&oauth_callback=" + urlEncode(base + "oauth/step2") + "&scope="
                    + urlEncode("https://mail.google.com/") + "&oauth_signature="
                    + urlEncode(hmac(consumer_secret + "&", base_string));
            final String reply = Browser.getHtml(url, null);
            // request_token est URL encoded
            final String request_token = parseReply("oauth_token", reply);
            // request_token_secret est URL encoded
            final String request_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            if (request_token == null || request_token_secret == null) {
                log.error("token error: token=" + request_token + " - token_secret=" + request_token_secret);
                return;
            }
            map_request_token.put(urlDecode(request_token), urlDecode(request_token_secret));

            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location",
                    "https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=" + request_token);
            final PrintWriter out = response.getWriter();
            out.println(
                    "<html><body>click <a href='https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token="
                            + request_token + "'>here</a></body></html>");
        }

        if (request.getPathInfo().equals("/step2")) {
            final String verifier = request.getParameter("oauth_verifier");
            // request_token n'est pas URL encoded
            final String request_token = request.getParameter("oauth_token");
            // request_token_secret n'est pas URL encoded
            final String request_token_secret = map_request_token.get(request_token);

            log.debug("oauthtoken=" + request_token);
            log.debug("oauthtokensecret=" + request_token_secret);
            log.debug("verifier=" + verifier);

            String nonce = nonce();
            String now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            String base_string = "GET&" + urlEncode("https://www.google.com/accounts/OAuthGetAccessToken") + "&"
                    + urlEncode("oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                            + urlEncode(request_token) + "&oauth_verifier=" + urlEncode(verifier)
                            + "&oauth_version=1.0");

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string)));

            String url = "https://www.google.com/accounts/OAuthGetAccessToken?oauth_consumer_key=www.vpnoverdns.com&oauth_nonce="
                    + nonce + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                    + urlEncode(request_token) + "&oauth_verifier=" + urlEncode(verifier)
                    + "&oauth_version=1.0&oauth_signature="
                    + urlEncode(hmac(consumer_secret + "&" + request_token_secret, base_string));

            final String reply = Browser.getHtml(url, null);
            // access token est URL encoded
            final String access_token = parseReply("oauth_token", reply);
            // access_token_secret est URL encoded
            final String access_token_secret = parseReply("oauth_token_secret", reply);
            log.debug("oauthaccesstoken=" + access_token);
            log.debug("oauthaccesstokensecret=" + access_token_secret);

            nonce = nonce();
            now = now();
            log.debug("nonce=" + nonce);
            log.debug("now=" + now);

            base_string = "GET&" + urlEncode("https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/")
                    + "&"
                    + urlEncode("oauth_consumer_key=www.vpnoverdns.com&oauth_nonce=" + nonce
                            + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + now + "&oauth_token="
                            + access_token + "&oauth_version=1.0");

            // oauth_token=\"$oauthaccesstoken\",oauth_version=\"1.0\",oauth_signature=\"$digestencoded\"" | read URL

            log.debug("digestencoded="
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string)));

            url = "GET https://mail.google.com/mail/b/alexandre.fenyo2@gmail.com/imap/ oauth_consumer_key=\"www.vpnoverdns.com\",oauth_nonce=\""
                    + nonce + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + now
                    + "\",oauth_token=\"" + access_token + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + urlEncode(hmac(consumer_secret + "&" + urlDecode(access_token_secret), base_string))
                    + "\"";
            log.debug(org.apache.commons.codec.binary.Base64.encodeBase64String(url.getBytes("UTF-8")));

        }

    } catch (InvalidKeyException ex) {
        log.error(ex.toString());
    } catch (NoSuchAlgorithmException ex) {
        log.error(ex.toString());
    }
}