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:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java

@Override
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    FedizContext fedContext = federationConfig.getFedizContext();
    LOG.debug("Federation context: {}", fedContext);

    if (hrequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
            || hrequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Metadata document requested");
        }/*  w  w w.  j av a  2s.c  o  m*/
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        try {
            Document metadata = wfProc.getMetaData(hrequest, fedContext);
            out.write(DOM2Writer.nodeToString(metadata));
            return;
        } catch (Exception ex) {
            LOG.warn("Failed to get metadata document: " + ex.getMessage());
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    String redirectUrl = null;
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());

        RedirectionResponse redirectionResponse = wfProc.createSignInRequest(hrequest, fedContext);
        redirectUrl = redirectionResponse.getRedirectionURL();

        if (redirectUrl == null) {
            LOG.warn("Failed to create SignInRequest.");
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create SignInRequest.");
        }

        Map<String, String> headers = redirectionResponse.getHeaders();
        if (!headers.isEmpty()) {
            for (String headerName : headers.keySet()) {
                hresponse.addHeader(headerName, headers.get(headerName));
            }
        }

    } catch (ProcessingException ex) {
        System.err.println("Failed to create SignInRequest: " + ex.getMessage());
        LOG.warn("Failed to create SignInRequest: " + ex.getMessage());
        hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
    }

    preCommence(hrequest, hresponse);
    if (LOG.isInfoEnabled()) {
        LOG.info("Redirecting to IDP: " + redirectUrl);
    }
    hresponse.sendRedirect(redirectUrl);

}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

private void handle(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    logger.debug("Handling request for \"" + request.getRequestURL() + "\"");
    try {/*  ww w  .j a  va2  s  . c  o m*/

        List<String> userLogins = null;
        if (isShareRequest(request)) {
            userLogins = MySQLOAuthProvider2.getShareUsers(request.getParameter("share"));
            if (null == userLogins || userLogins.isEmpty()) { // open to any user TODO check NULL user
                authorizeRequestToken(request, response, null);
                return;
            }
            // returns not found exception if not found share
        }

        if (isOpenIdResponse(request)) {
            logger.debug("Handle OpenID");
            handleOpenidResponse(request, response);
        } else { // initial login
            logger.debug("Initiate");
            String userName = checkCertificate(request);
            if (null != userName) { // made X.509 authentication
                logger.debug("Certificate checked. Username: " + userName);

                if (!UserHelper.userExists(userName)) {
                    UserHelper.addDefaultUser(userName);
                }

                authorizeRequestToken(request, response, userName);
            } else { // need to do openid
                logger.debug("OpenID init");
                String provider = request.getParameter("provider");
                String idLess = getIdentityless(provider);

                // set cookie for cases when user came directly to authorize from 3rd party application
                if (null != request.getParameter("oauth_token")) {
                    OauthCookie cookie = new OauthCookie();
                    cookie.setRequestToken(request.getParameter("oauth_token"));
                    cookie.setCallbackUrl(request.getParameter("oauth_callback"));
                    cookie.setRegion(conf.getString("region"));
                    cookie.setShareId(request.getParameter("share"));
                    response.addCookie(new Cookie(OauthCookie.COOKIE_NAME, cookie.toString()));
                    logger.debug("Created third party app cookie.");
                }

                String error = initiateOpenid(request, response, idLess);
                if (error != null)
                    throw new Oops(error);
            }
        }
    }
    // for local error-reporting, use a private Exception class, Oops (see below)
    catch (Oops e) {
        handleError(request, response, e.getMessage());
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {/*from  ww  w.  ja va 2  s.co m*/
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

From source file:ch.entwine.weblounge.kernel.security.SecurityFilter.java

/**
 * {@inheritDoc}//from w  w w.  j  a v  a  2 s  . c  o m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    Site site = null;
    if (!(request instanceof HttpServletRequest)) {
        logger.warn("Received plain servlet request and don't know what to do with it");
        return;
    }

    // Try to map the request to a site
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    URL url = UrlUtils.toURL(httpRequest, false, false);
    site = sites.findSiteByURL(url);
    if (site == null) {
        logger.debug("Request for {} cannot be mapped to any site", httpRequest.getRequestURL());
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set the site in the security service
    try {
        logger.trace("Request to {} mapped to site '{}'", httpRequest.getRequestURL(), site.getIdentifier());
        securityService.setSite(site);

        // Select appropriate security filter and apply it
        Filter siteSecurityFilter = siteFilters.get(site);
        if (siteSecurityFilter != null) {
            logger.trace("Security for '{}' is handled by site specific security configuration");
            siteSecurityFilter.doFilter(request, response, chain);
        } else {
            logger.trace("Security for '{}' is handled by default security configuration");
            defaultSecurityFilter.doFilter(request, response, chain);
        }
    } finally {
        securityService.setSite(null);
    }

}

From source file:com.all.backend.web.controller.LoginServerController.java

@RequestMapping(method = POST, value = "/signup")
@ResponseBody/*  ww w. ja  v  a  2  s.  co m*/
public String signup(@RequestBody String jsonUser, HttpServletRequest request) {
    log.info("\nACTION:SignUp");
    User user = JsonConverter.toBean(jsonUser, User.class);
    StringBuffer requestURL = request.getRequestURL();
    String url = getEnvironment(requestURL);
    try {
        userService.signup(user, url);
    } catch (UserAlreadyRegisteredException e) {
        return USER_ALREADY_REGISTERED.toString();
    } catch (Exception e) {
        return SERVER_ERROR.toString();
    }
    PendingEmail pendingEmail = createPendingEmail(user);
    BackendServiceHelper.queue(emailService, BackendConstants.SEND_SIGNUP_EMAIL_REQUEST_TYPE, pendingEmail);
    return OK.toString();
}

From source file:com.firstclarity.magnolia.study.blossom.sample.TourComponent.java

@RequestMapping("/tour")
public String handleRequest(ModelMap model, HttpSession session, HttpServletRequest request, Content content) {

    String articleCode = content.getNodeData("articleCode").getString();

    Tour tour = salesApplicationWebService.getTour(articleCode);

    if ("add".equals(request.getParameter("action"))) {

        ShoppingCart shoppingCart = ShoppingCart.getShoppingCart(session);

        shoppingCart.addItem(tour, Integer.parseInt(request.getParameter("quantity")));

        return "redirect:" + request.getRequestURL();
    }//from  w  ww . j av a  2  s .c om

    model.put("tour", tour);

    return "mymodule/components/tour.jsp";
}

From source file:com.puglieseweb.app.web.templates.components.TourComponent.java

@RequestMapping("/tour")
public String render(ModelMap model, HttpSession session, HttpServletRequest request, Content content) {

    String articleCode = content.getNodeData("articleCode").getString();

    Tour tour = salesApplicationWebService.getTour(articleCode);

    if ("add".equals(request.getParameter("action"))) {

        ShoppingCart shoppingCart = ShoppingCart.getShoppingCart(session);

        shoppingCart.addItem(tour, Integer.parseInt(request.getParameter("quantity")));

        return "redirect:" + request.getRequestURL();
    }//w  w  w  . j a  v a 2 s.co m

    model.put("tour", tour);

    return "components/tour.jsp";
}

From source file:com.puglieseweb.app.web.templates.components.BookComponent.java

@RequestMapping("/book")
public String render(ModelMap model, HttpSession session, HttpServletRequest request, Content content) {

    String articleCode = content.getNodeData("articleCode").getString();

    Book book = salesApplicationWebService.getBook(articleCode);

    if ("add".equals(request.getParameter("action"))) {

        ShoppingCart shoppingCart = ShoppingCart.getShoppingCart(session);

        shoppingCart.addItem(book, Integer.parseInt(request.getParameter("quantity")));

        return "redirect:" + request.getRequestURL();
    }//from w ww  .j  av  a  2s  .co m

    model.put("book", book);

    return "components/book.jsp";
}

From source file:org.cloudifysource.rest.command.CommandManager.java

/**
 * Constructor takes as input the entire commands URI, held in the request
 * and the root object from which to begin invocation.
 * @param request - the commands request 
 * @param root - the root command's object
 *//*  ww  w  .  j a  v  a  2  s.  co m*/
public CommandManager(HttpServletRequest request, Object root) {
    final String prefix = "/admin/";
    String executionPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    if (executionPath.endsWith("/")) {
        executionPath = executionPath.substring(0, executionPath.length() - 1);
    }
    if (!executionPath.startsWith(prefix)) {
        throw new IllegalArgumentException("Bad request URL " + request.getRequestURL());
    }
    String restUrl = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath();
    this.commandURL = restUrl + executionPath;
    initilizeCommandList(executionPath.substring(prefix.length()), root);
}

From source file:se.skltp.cooperation.web.rest.exception.DefaultExceptionHandler.java

private void buildErrorMessage(HttpServletRequest request, Exception e, HttpStatus status,
        ProblemDetail error) {/*from   w ww . j av a  2s . c  o  m*/
    try {
        error.setType(new URI("http://httpstatus.es/" + status.value()));
    } catch (URISyntaxException e1) {
        log.error("Unable to set error type", e);
    }
    error.setTitle(status.getReasonPhrase());
    error.setStatus(status.value());
    error.setDetail(e.getMessage());
    String url = request.getRequestURL().toString();
    if (request.getQueryString() != null) {
        url = url + "?" + request.getQueryString();
    }
    error.setInstance(url);
}