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.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "WEBHDFS";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(/*from w ww  .  java2s .co m*/
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream())
            .andAnswer(new IAnswer<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @Override
                        public void write(int b) throws IOException {
                            throw new IOException("unreachable-host");
                        }
                    };
                }
            }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    WebHdfsHaDispatch dispatch = new WebHdfsHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatchTest.java

@Test
public void testConnectivityFailover() throws Exception {
    String serviceName = "OOZIE";
    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
    descriptor.addServiceConfig(// w  w w  . j a  v  a 2 s  .c o m
            HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
    HaProvider provider = new DefaultHaProvider(descriptor);
    URI uri1 = new URI("http://unreachable-host");
    URI uri2 = new URI("http://reachable-host");
    ArrayList<String> urlList = new ArrayList<String>();
    urlList.add(uri1.toString());
    urlList.add(uri2.toString());
    provider.addHaService(serviceName, urlList);
    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);

    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME))
            .andReturn(provider).anyTimes();

    BasicHttpParams params = new BasicHttpParams();

    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
    EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes();
    EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes();
    EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes();

    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0))
            .once();
    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1))
            .once();

    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
    EasyMock.expect(outboundResponse.getOutputStream())
            .andAnswer(new IAnswer<SynchronousServletOutputStreamAdapter>() {
                @Override
                public SynchronousServletOutputStreamAdapter answer() throws Throwable {
                    return new SynchronousServletOutputStreamAdapter() {
                        @Override
                        public void write(int b) throws IOException {
                            throw new IOException("unreachable-host");
                        }
                    };
                }
            }).once();
    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
    DefaultHaDispatch dispatch = new DefaultHaDispatch();
    dispatch.setHttpClient(new DefaultHttpClient());
    dispatch.setHaProvider(provider);
    dispatch.setServiceRole(serviceName);
    dispatch.init();
    long startTime = System.currentTimeMillis();
    try {
        dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
    } catch (IOException e) {
        //this is expected after the failover limit is reached
    }
    long elapsedTime = System.currentTimeMillis() - startTime;
    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
    //test to make sure the sleep took place
    Assert.assertTrue(elapsedTime > 1000);
}

From source file:edu.harvard.i2b2.Oauth2.OAuthWS.java

@GET
@Path("getAuthCode")
public Response getAuthorizationCode(@Context HttpServletRequest request) {
    OAuthAuthzResponse oar;//from  w  w w.  j  av a  2 s.c o  m
    basePath = request.getRequestURL().toString()
            .replaceAll(OAuthWS.class.getAnnotation(Path.class).value().toString() + "$", "")
            .split("client")[0];

    try {
        oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
        String code = oar.getCode();
        String redirectUrl = oar.getParam("redirect_uri");
        logger.info("gotAuthCode:" + code);
        // return Response.ok().entity("AuthCode:" + code).build();
        String accessToken = exchangeOAuthCodeForAccessToken(code, "fcclient1", "csecret1", redirectUrl);

        return Response.ok().entity("Access Token:" + accessToken).type(MediaType.TEXT_PLAIN).build();
        //String msg = accessResource(accessToken);
        //return Response.ok().entity(msg).type(MediaType.TEXT_PLAIN).build();
    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        return errorResponse(e);

    }

}

From source file:com.bluexml.side.Framework.alfresco.shareLanguagePicker.CustomWebScriptServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Processing request (" + req.getMethod() + ") " + req.getRequestURL()
                + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
    }//from  w  w  w. j  ava2 s.c  o m

    if (req.getCharacterEncoding() == null) {
        req.setCharacterEncoding("UTF-8");
    }
    // initialize the request context
    RequestContext context = null;
    try {
        context = FrameworkHelper.initRequestContext(req);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    LanguageSetter.setLanguageFromLayoutParam(req, context);

    WebScriptServletRuntime runtime = new WebScriptServletRuntime(container, authenticatorFactory, req, res,
            serverProperties);
    runtime.executeScript();
}

From source file:net.ljcomputing.core.controler.GlobalExceptionController.java

/**
 * Handle all required value exceptions.
 *
 * @param req the req//from   w  ww  . j  a  va  2  s .  c o m
 * @param exception the exception
 * @return the error info
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(RequiredValueException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorInfo handleAllRequiredValueExceptions(HttpServletRequest req, Exception exception) {
    logger.warn("A required value is missing : {}:", req.getRequestURL().toString());

    return new ErrorInfo(getCurrentTimestamp(), HttpStatus.BAD_REQUEST, req.getRequestURL().toString(),
            exception);
}

From source file:com.lyh.licenseworkflow.web.filter.LoginFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    StringBuffer buffer = httpRequest.getRequestURL();// url
    String queryString = httpRequest.getQueryString();// ?
    HttpSession session = httpRequest.getSession();
    //?/*from   w  w w .j  a va  2  s. c om*/
    String wonderUrl = URLEncoder.encode(httpRequest.getRequestURI() + "?" + httpRequest.getQueryString(),
            "UTF-8");
    String fullUrl = buffer.toString();// url???web??
    boolean checkPermission = true;// ?????CSSJSJVM???
    for (String ingoreUrl : ingoreUrls) {
        if (fullUrl.indexOf(ingoreUrl) != -1) {// URL???????
            checkPermission = false;
            break;
        }
    }
    if (!checkPermission) {// ???
        filterChain.doFilter(httpRequest, httpResponse);
    } else {// ?????
        User loginUser = (User) httpRequest.getSession().getAttribute(LicenseWorkFlowConstants.SESSION_USER);
        if (loginUser == null) {
            //??
            //session
            //                httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.action?wonderUrl=" + wonderUrl);
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.action");
            return;
        } else {
            filterChain.doFilter(httpRequest, httpResponse);
        }
    }
}

From source file:com.sonicle.webtop.core.app.servlet.Login.java

private String getBaseUrl(HttpServletRequest request) {
    StringBuffer url = request.getRequestURL();
    String uri = request.getRequestURI();
    String ctx = request.getContextPath();
    return url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
}

From source file:fr.treeptik.cloudunit.config.Http401EntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg)
        throws IOException, ServletException {

    // Maybe change the log level...
    log.warn("Access Denied [ " + request.getRequestURL().toString() + "] : " + arg.getMessage());

    // Trace message to ban intruders with fail2ban
    //generateLogTraceForFail2ban();

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access unauthorized");
}

From source file:ar.com.zauber.commons.web.cache.api.filter.HttpCacheFilter.java

/** @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */
public final void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    LOGGER.debug("Serving {}", httpRequest.getRequestURL());

    HttpCacheRule matchedRule = null;/*w w w  .  jav  a  2 s . c  o m*/
    MatchData matchData = null;
    for (HttpCacheRule cacheRule : this.cacheRules) {
        matchData = cacheRule.getMatcher().matches(httpRequest);
        if (matchData != null) {
            matchedRule = cacheRule;
            break;
        }
    }

    if (matchedRule == null) {
        chain.doFilter(httpRequest, httpResponse);
    } else {
        ExtendedHttpServletResponse extendedResponse = new ExtendedHttpServletResponse(httpResponse);
        boolean endRequest = matchedRule.getAction().preProcess(matchData, httpRequest, extendedResponse);
        if (!endRequest) {
            chain.doFilter(httpRequest, extendedResponse);
            matchedRule.getAction().postProcess(matchData, httpRequest, extendedResponse);
        }
    }
}

From source file:nl.dtls.fairdatapoint.api.controller.MetadataController.java

@ApiOperation(value = "Catalog metadata")
@RequestMapping(value = "/{catalogID:[^.]+}", method = RequestMethod.GET, produces = { "text/turtle",
        "application/ld+json", "application/rdf+xml", "text/n3" })
public String getCatalogMetaData(@PathVariable final String catalogID, HttpServletRequest request,
        HttpServletResponse response) {//from w w  w. ja  va  2s.c  o m
    LOGGER.info("Request to get CATALOG metadata {}", catalogID);
    LOGGER.info("GET : " + request.getRequestURL());
    String responseBody;
    String contentType = request.getHeader(HttpHeaders.ACCEPT);
    RDFFormat requesetedContentType = HttpHeadersUtils.getRequestedAcceptHeader(contentType);
    try {
        responseBody = fairMetaDataService.retrieveCatalogMetaData(catalogID, requesetedContentType);
        HttpHeadersUtils.set200ResponseHeaders(responseBody, response, requesetedContentType);
    } catch (FairMetadataServiceException ex) {
        responseBody = HttpHeadersUtils.set500ResponseHeaders(response, ex);
    }
    LoggerUtils.logRequest(LOGGER, request, response);
    return responseBody;
}