Example usage for javax.servlet.http HttpServletRequest getRequestURL

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

Introduction

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

Prototype

public StringBuffer getRequestURL();

Source Link

Document

Reconstructs the URL the client used to make the request.

Usage

From source file:edu.usc.lunchnlearn.elasticsearch.interceptor.BreadCrumbInterceptor.java

private Crumb getCurrentCrumb(HttpServletRequest request, Map<String, Long> breadcrumbUrls,
        Map<Long, Crumb> breadcrumbs, ModelAndView modelAndView) {
    Crumb crumb = new Crumb();

    StringBuffer stringBuffer = request.getRequestURL();
    if (request.getQueryString() != null) {
        stringBuffer.append("?").append(request.getQueryString());
    }/*from  w ww  . j  a  va  2s. c o  m*/
    crumb.setUrl(stringBuffer.toString());

    //if the exact URL has already been requested, use that crumb instead of creating a new one.
    if (breadcrumbUrls.containsKey(crumb.getUrl())) {
        return breadcrumbs.get(breadcrumbUrls.get(crumb.getUrl()));
    }

    //set the display text of the breadcrumb
    crumb.setDisplayText("");

    if (modelAndView.getModelMap().containsAttribute("title")) {
        crumb.setDisplayText((String) modelAndView.getModelMap().get("title"));
    } else {
        for (String uri : uriDisplayTextMapping.keySet()) {
            if (crumb.getUrl().contains(uri)) {
                crumb.setDisplayText(uriDisplayTextMapping.get(uri));
                break;
            }
        }
    }

    //set the parent value
    if (request.getParameterMap().containsKey("x")) {
        if (StringUtils.isNumeric(request.getParameter("x"))) {
            crumb.setParentX(Long.parseLong(request.getParameter("x")));
        }
    }

    //set the time in millis for X
    crumb.setX(System.currentTimeMillis());

    return crumb;
}

From source file:nl.surfnet.coin.api.playground.OAuthClientController.java

@RequestMapping(value = { "/test" }, method = RequestMethod.GET)
public String socialQueries(ModelMap modelMap, HttpServletRequest request) throws IOException {

    setupModelMap(new ApiSettings(request.getRequestURL().toString()), "step1", request, modelMap, null);
    modelMap.addAttribute("versionIdentifier", versionIdentifier);
    return "oauth-client";
}

From source file:eionet.cr.web.filters.HomespaceUrlFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    // Pass on if not a HTTP request.
    if (!(servletRequest instanceof HttpServletRequest)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;//w ww  . ja v a  2s.c  o  m
    }

    // Instantiate local variables for HTTP request, response and request-URL
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    String requestURL = httpRequest.getRequestURL().toString();

    boolean isProjectFolder = FolderUtil.isProjectFolder(requestURL);

    String contextPath = httpRequest.getContextPath();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("httpRequest.getRequestURL() = " + requestURL);
        LOGGER.trace("httpRequest.getRequestURI() = " + httpRequest.getRequestURI());
        LOGGER.trace("httpRequest.getContextPath() = " + contextPath);
        LOGGER.trace("httpRequest.getServletPath() = " + httpRequest.getServletPath());
        LOGGER.trace("httpRequest.getPathInfo() = " + httpRequest.getPathInfo());
    }

    // Parse path info if it is not null and its length is greater than 1
    // (because if its equal to 1, then it is "/", meaning the application's root URI).
    String pathInfo = httpRequest.getPathInfo();
    if (pathInfo != null && pathInfo.length() > 1) {

        int i = pathInfo.indexOf('/', 1);
        if (i != -1 && pathInfo.length() > (i + 1)) {

            try {
                // Prepare the default redirect location.
                String queryString = "?uri=" + URLEncoder.encode(requestURL, "UTF-8");
                String redirectLocation = contextPath + Util.getUrlBinding(ExportTriplesActionBean.class)
                        + queryString;

                // Override the prepared redirect location in the below special cases.
                if (DAOFactory.get().getDao(HelperDAO.class).isTabularDataSubject(requestURL)) {
                    // The requested URL is a subject in tabular data (i.e. CSV or TSV) file.
                    redirectLocation = contextPath + TabularDataServlet.URL_PATTERN + queryString;
                    LOGGER.debug("URL points to tabular data subject, redirecting to: " + redirectLocation);
                    // if project file, do not check the filestore in ordinary way
                } else if (isStoredFile(pathInfo, isProjectFolder) && !isRdfXmlPreferred(httpRequest)) {
                    // The requested URL is a stored file, and requester wants original copy (i.e. not triples)
                    redirectLocation = contextPath + DownloadServlet.URL_PATTERN + queryString;
                    LOGGER.debug("URL points to stored file, redirecting to: " + redirectLocation);
                } else if (isSparqlBookmark(pathInfo)) {
                    if (isRdfXmlPreferred(httpRequest)) {
                        redirectLocation = contextPath + Util.getUrlBinding(ExportTriplesActionBean.class)
                                + queryString + "&exportProperties=";
                    } else {
                        redirectLocation = contextPath + Util.getUrlBinding(ViewActionBean.class) + queryString;
                    }
                }

                // Redirect to the location resolved above.
                httpResponse.sendRedirect(redirectLocation);
                return;
            } catch (DAOException e) {
                throw new ServletException(e.getMessage(), e);
            }
        }
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest.java

public void applyRequest(final HttpServletRequest request) {
    setClientIP(request.getRemoteAddr());
    setPath(request.getPathInfo());/*from w  w  w  .jav a 2  s.c  o m*/
    setQueryString(request.getQueryString());
    setHostname(request.getServerName());
    setRequestedUrl(request.getRequestURL().toString());
    setUri(request.getRequestURI());

    final String xmm = request.getHeader(X_MM_CLIENT_IP);
    final String fip = request.getParameter(FAKE_IP);

    if (xmm != null) {
        setClientIP(xmm);
    } else if (fip != null) {
        setClientIP(fip);
    }

    final Map<String, String> headers = new HashMap<String, String>();
    final Enumeration<?> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = (String) headerNames.nextElement();
        final String value = request.getHeader(name);
        headers.put(name, value);
    }
    setHeaders(headers);
    secure = request.isSecure();
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

/**
 * Constructs an instance of the inner class WebProxy.HttpRequest with a url containing "{" and checks that the
 * resulting uri escapes the curly brackets correctly.
 *
 * @throws NoSuchMethodException/*from  w  w w .ja va2 s.c o m*/
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@Test
public void testGetUri() throws Exception {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    when(servletRequest.getRequestURL()).thenReturn(new StringBuffer("http://somedomain.dk?id=%7B12345%7D"));
    WebProxy.HttpRequest http_request = new WebProxy.HttpRequest(servletRequest);
    URI uri = http_request.getURI();
    assertEquals("Expect uri to be escaped", "http://somedomain.dk?id=%7B12345%7D", uri.toString());
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.LoginExternalAuthReturn.java

/**
 * <pre>//from   w  w w .  j a  v a 2 s.c o  m
 * Returning from the external authorization server. If we were successful,
 * the header will contain the name of the user who just logged in.
 * 
 * Deal with these possibilities: 
 * - The header name was not configured in runtime.properties. Complain.
 * - No username: the login failed. Complain 
 * - User corresponds to a User acocunt. Record the login. 
 * - User corresponds to an Individual (self-editor). 
 * - User is not recognized.
 * 
 * On entry, we expect to find:
 * - A LoginProcessBean, which will give us the afterLoginUrl if the login
 *      succeeds.
 * - A referrer URL, to which we will redirect if the login fails.
 *      TODO: is this equal to LoginProcessBean.getLoginPageUrl()?
 * These are removed on exit.
 * </pre>
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        @SuppressWarnings("unchecked")
        Enumeration<String> names = req.getHeaderNames();

        log.debug("------------request:" + req.getRequestURL());
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            log.debug(name + "=" + req.getHeader(name));
        }
    }

    String externalAuthId = ExternalAuthHelper.getHelper(req).getExternalAuthId(req);
    log.debug("externalAuthID='" + externalAuthId + "'");

    if (externalAuthId == null) {
        complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, messageLoginFailed(req));
        return;
    }

    String afterLoginUrl = LoginProcessBean.getBean(req).getAfterLoginUrl();
    removeLoginProcessArtifacts(req);

    UserAccount userAccount = getAuthenticator(req).getAccountForExternalAuth(externalAuthId);

    if (!getAuthenticator(req).isUserPermittedToLogin(userAccount)) {
        log.debug("Logins disabled for " + userAccount);
        complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, messageLoginDisabled(req));
        return;
    }

    if (userAccount == null) {
        log.debug("Creating new account for " + externalAuthId + ", return to '" + afterLoginUrl + "'");
        UserAccountsFirstTimeExternalPage.setExternalLoginInfo(req, externalAuthId, afterLoginUrl);
        resp.sendRedirect(UrlBuilder.getUrl("/accounts/firstTimeExternal"));
        return;
    }

    try {
        log.debug("Logging in as " + userAccount.getUri());
        getAuthenticator(req).recordLoginAgainstUserAccount(userAccount, AuthenticationSource.EXTERNAL);
        new LoginRedirector(req, afterLoginUrl).redirectLoggedInUser(resp);
        return;
    } catch (LoginNotPermitted e) {
        // should have been caught by isUserPermittedToLogin()
        log.debug("Logins disabled for " + userAccount);
        complainAndReturnToReferrer(req, resp, ATTRIBUTE_REFERRER, messageLoginDisabled(req));
        return;
    }
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

protected String getRequestPID(HttpServletRequest request, String delimiter) throws DecoderException {
    StringBuffer urlBuffer = request.getRequestURL();
    int objectStart = urlBuffer.indexOf(delimiter);
    String pid = urlBuffer.substring(objectStart + delimiter.length(), urlBuffer.length());
    String decodedPID = null;/*from w  w  w  .jav  a  2  s  . c om*/
    try {
        decodedPID = urlCodec.decode(pid, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        decodedPID = urlCodec.decode(pid);
    }
    logger.info("decoding GUID/PID: " + pid + " to " + decodedPID);
    return decodedPID;
}

From source file:edu.harvard.i2b2.fhir.oauth2.ws.OAuth2TokenEndpoint.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response authorize(@Context HttpServletRequest request)
        throws OAuthSystemException, IOException, URISyntaxException {

    try {//from  w  ww  . ja v  a2  s.  c o m
        logger.info("got url:" + request.getRequestURL());

        Enumeration<String> kl = request.getParameterNames();
        while (kl.hasMoreElements()) {
            String k = kl.nextElement();
            logger.debug(k + "->" + request.getParameter(k));
        }

        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

        // find if AuthToken was issued, from db
        String authCode = oauthRequest.getCode();
        AuthToken authToken = authTokenBean.find(authCode);
        if (authToken == null) {
            logger.debug("authToken is not found");

            return buildBadAuthCodeResponse();
        }
        logger.debug("authToken is " + authToken.toString());

        // check if clientid is valid
        if (!checkClientId(oauthRequest.getClientId(), authToken)) {
            return buildInvalidClientIdResponse();
        }

        // check if client_secret is valid
        if (!checkClientSecret(oauthRequest.getClientSecret())) {
            return buildInvalidClientSecretResponse();
        }

        // do checking for different grant types
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!checkAuthCode(authToken, oauthRequest.getParam(OAuth.OAUTH_CODE))) {
                return buildBadAuthCodeResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPass(oauthRequest.getUsername(), oauthRequest.getPassword(), authToken)) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            // refresh token is not supported in this implementation
            // buildInvalidUserPassResponse();
            //buildAccessTokenNotSupportedResponse();
        }

        logger.trace("authToken:" + authToken);
        String state = authToken.getState();
        String patientId = authToken.getPatient();

        AccessToken accessToken = accessTokenBean.createAccessTokenAndDeleteAuthToken(authToken);

        URI fhirBase = HttpHelper.getBasePath(request, serverConfigs);
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken.getTokenString()).setExpiresIn("3600")
                .setScope(accessToken.getScope()).setParam("token_type", "Bearer").setParam("state", state)
                .setParam("patient", patientId)//"1000000005")//authToken.getPatient())
                .setParam("need_patient_banner", "true")
                .setParam("smart_style_url", fhirBase.toString() + "smartstyleuri").buildJSONMessage();
        logger.trace("pat:" + authToken.getPatient());
        logger.info("returning res:" + response.getBody());

        return Response.status(response.getResponseStatus()).entity(response.getBody()).build();

    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
    }
}

From source file:LogFilter.java

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

    HttpServletRequest req = null;
    String id = config.getInitParameter("log-id");

    if (id == null)
        id = "unknown";

    if (log != null && (request instanceof HttpServletRequest)) {

        req = (HttpServletRequest) request;
        log.info("Log id:" + id + ": Request received from: " + req.getRemoteHost() + " for "
                + req.getRequestURL());
    }// w w w  .  ja  v  a  2s  . c  o m

    chain.doFilter(request, response);
}

From source file:org.sakaiproject.imagegallery.web.MultiFileUploaderController.java

public void multiFileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (log.isInfoEnabled())
        log.info("req contextPath=" + request.getContextPath() + ", pathInfo=" + request.getPathInfo()
                + ", query=" + request.getQueryString() + ", URI=" + request.getRequestURI() + ", URL="
                + request.getRequestURL() + ", servlet=" + request.getServletPath());
    if (request instanceof MultipartHttpServletRequest) {
        String newImageId = storeNewImage((MultipartHttpServletRequest) request);
        response.setContentType("text/plain");
        PrintWriter responseWriter = response.getWriter();
        responseWriter.print(newImageId);
        responseWriter.close();/*from ww  w.j a v  a2s  .  c om*/
    }
}