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:csiro.pidsvc.servlet.info.java

/**
 * Echoes HTTP headers./*from ww w. j a va  2  s  . co  m*/
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws URISyntaxException
 */
protected void echo(HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    String ret = "HTTP " + request.getMethod() + " " + request.getRequestURL() + "?" + request.getQueryString()
            + "\n\n";

    // Retrieve HTTP headers.
    for (@SuppressWarnings("unchecked")
    Enumeration<String> header = request.getHeaderNames(); header.hasMoreElements();) {
        String headerName = (String) header.nextElement();
        ret += headerName + ": " + request.getHeader(headerName) + "\n";
    }

    response.setContentType("text/plain");
    response.getWriter().write(ret);
}

From source file:com.chessix.vas.web.RequestProcessingTimeInterceptor.java

@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) throws Exception {
    if (log.isDebugEnabled()) {
        final long startTime = (Long) request.getAttribute(START_TIME);
        log.debug("Request URL::{}:: Time Taken={} ms", request.getRequestURL(),
                System.currentTimeMillis() - startTime);
    }/*from  w ww . ja  v a2  s. c  om*/
}

From source file:io.kamax.mxisd.controller.identity.v1.SessionRestController.java

@RequestMapping(value = "/validate/{medium}/requestToken")
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium)
        throws IOException {
    log.info("Request {}: {}", request.getMethod(), request.getRequestURL(), request.getQueryString());
    if (ThreePidMedium.Email.is(medium)) {
        SessionEmailTokenRequestJson req = parser.parse(request, SessionEmailTokenRequestJson.class);
        return gson.toJson(
                new Sid(mgr.create(request.getRemoteHost(), new ThreePid(req.getMedium(), req.getValue()),
                        req.getSecret(), req.getAttempt(), req.getNextLink())));
    }/*from  ww w .j av a  2 s  . co m*/

    if (ThreePidMedium.PhoneNumber.is(medium)) {
        SessionPhoneTokenRequestJson req = parser.parse(request, SessionPhoneTokenRequestJson.class);
        ThreePid threepid = new ThreePid(req.getMedium(), req.getValue());

        String sessionId = mgr.create(request.getRemoteHost(), threepid, req.getSecret(), req.getAttempt(),
                req.getNextLink());

        JsonObject res = new JsonObject();
        res.addProperty("sid", sessionId);
        res.addProperty(threepid.getMedium(), threepid.getAddress());
        return gson.toJson(res);
    }

    JsonObject obj = new JsonObject();
    obj.addProperty("errcode", "M_INVALID_3PID_TYPE");
    obj.addProperty("error", medium + " is not supported as a 3PID type");
    response.setStatus(HttpStatus.SC_BAD_REQUEST);
    return gson.toJson(obj);
}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

protected ResponseEntity<FileInfo> createFileInfoResponseEntity(HttpServletRequest request, FileDescriptor fd) {
    FileInfo fileInfo = new FileInfo(fd.getId(), fd.getName(), fd.getSize());

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString())
            .path("/{id}").buildAndExpand(fd.getId().toString());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uriComponents.toUri());
    return new ResponseEntity<>(fileInfo, httpHeaders, HttpStatus.CREATED);
}

From source file:at.plechinger.spring.security.scribe.ScribeAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException, IOException, ServletException {

    String callbackUrl = request.getRequestURL().append("?").append(request.getQueryString()).toString();

    LOG.log(Level.DEBUG, "callbackUrl " + callbackUrl);

    String configMatch = request.getParameter(configMatchParameter);

    LOG.log(Level.DEBUG, "configMatch: " + configMatch);

    ProviderConfiguration providerConfiguration = getMatchedProviderConfiguration(configMatch);

    HttpSession session = request.getSession(true);

    ServiceBuilder serviceBuilder = new ServiceBuilder().provider(providerConfiguration.getApiClass())
            .apiKey(providerConfiguration.getApiKey()).apiSecret(providerConfiguration.getApiSecret())
            .callback(callbackUrl);//w  ww .j  a  va  2s  .c o m

    //enable debug logging if enabled
    if (LOG.getLevel() == Level.DEBUG) {
        LOG.log(Level.DEBUG, "enable scribe debug mode");
        serviceBuilder.debug();
    }

    OAuthService oAuthService = serviceBuilder.build();

    if (!providerConfiguration.isAuthCodeProvided(request)) {
        Token requestToken = null;
        try {
            requestToken = oAuthService.getRequestToken();
        } catch (UnsupportedOperationException e) {
            //some networks dont support request tokens (eg. Facebook)
        }

        String authUrl = oAuthService.getAuthorizationUrl(requestToken);

        session.setAttribute(SESSION_TOKEN, requestToken);
        response.sendRedirect(authUrl);
        return null;
    } else {
        ScribeAuthentication scribeAuthentication = new ScribeAuthentication();
        String authCode = providerConfiguration.getAuthCode(request);
        Verifier verifier = new Verifier(authCode);
        Token requestToken = (Token) session.getAttribute(SESSION_TOKEN);

        Token accessToken = oAuthService.getAccessToken(requestToken, verifier);
        scribeAuthentication.setScribeToken(accessToken);
        scribeAuthentication.setRedirectUrl(callbackUrl);

        scribeAuthentication.setDetails(this.authenticationDetailsSource.buildDetails(request));

        scribeAuthentication.setProviderConfiguration(providerConfiguration);
        AuthenticationManager authenticationManager = this.getAuthenticationManager();
        Authentication success = authenticationManager.authenticate(scribeAuthentication);

        return success;
    }
}

From source file:com.music.web.util.ExceptionResolver.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*  w ww.ja v  a  2 s  .  com*/

    // the stacktrace will be printed by spring's DispatcherServlet
    // we are only logging the request url and headeres here
    logger.warn("An exception occurred when invoking the following URL: " + request.getRequestURL()
            + " . Requester IP is " + request.getRemoteAddr() + ", User-Agent: "
            + request.getHeader("User-Agent") + "; Message=" + ex.getMessage() + ": "
            + ex.getStackTrace()[0].getMethodName());

    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return null;
}

From source file:info.magnolia.blossom.sample.module.CommentsComponent.java

@RequestMapping("/comments")
public String render(ModelMap model, HttpServletRequest request, @RequestParam("action") String action,
        Content content) throws RepositoryException {

    if ("add".equals(action)) {
        writeComment(request, content);//from   w  w  w  . ja va  2  s .com
        return "redirect:" + request.getRequestURL();
    }
    if ("delete".equals(action)) {
        deleteComment(request, content);
        return "redirect:" + request.getRequestURL();
    }

    model.addAttribute("comments", readComments(content));
    return "components/comments.jsp";
}

From source file:edu.harvard.i2b2.fhirserver.ws.OAuth2TokenEndpoint.java

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

    try {/*from   w  ww  .ja v  a  2 s. co 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())) {
            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();
        }

        final String accessTokenString = oauthIssuerImpl.accessToken();
        // database.addToken(accessToken);
        String resourceUserId = authToken.getResourceUserId();
        String i2b2Token = authToken.getI2b2Token();
        String i2b2Project = authToken.getI2b2Project();
        String clientId = authToken.getClientId();
        String scope = authToken.getScope();

        accessTokenBean.createAccessTokenAndDeleteAuthToken(authCode, accessTokenString, resourceUserId,
                i2b2Token, i2b2Project, clientId, scope);

        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessTokenString).setExpiresIn("3600").buildJSONMessage();
        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:eu.morfeoproject.fast.catalogue.services.GenericServlet.java

protected void redirectToFormat(HttpServletRequest request, HttpServletResponse response, String format)
        throws IOException {
    String extension = MediaType.getExtension(format);
    extension = extension == null ? MediaType.getExtension(MediaType.APPLICATION_JSON) : extension;
    String url = request.getRequestURL().toString();
    url = (url.charAt(url.length() - 1) == '/') ? url.concat(extension) : url.concat("/" + extension);
    response.sendRedirect(url);/*from   w w  w . j a  v  a  2  s . com*/
}

From source file:io.dacopancm.jfee.managedController.EditarSocioBean.java

@PostConstruct
public void postConstruct() {
    Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap();/*from w  w w.j av  a 2s .  c o m*/
    if (params.containsKey("r")) {
        returnPage = params.get("r");
    } else {
        returnPage = "home";
    }
    try {
        HttpServletRequest htpr = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        if (htpr.getRequestURL().toString().contains("editarSocio")) {
            if (params.containsKey("socCi") && params.containsKey("h")) {
                String hash = UriUtils.decode(params.get("h"), "UTF-8");
                String ci = params.get("socCi");
                if (BCrypt.checkpw(ci, hash)) {
                    //TODO si es administrador no pasa nada pero
                    //si es socio probar q current socio login sea el mismo a modificar
                    selectedSocio = socioService.getSocioByCi(ci);
                }
            } else {

                User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

                selectedSocio = socioService.getSocioByCi(userDetails.getUsername());

            }
        } else {
            User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            selectedSocio = socioService.getSocioByCi(userDetails.getUsername());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }

}