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.ldp4j.apps.ldp4ro.servlets.Form2RDFServlet.java

/**
 * Upon receiving data from the RO creation form,
 * 1. parses the request to extract the form data
 * 2. converts them to RDF to generate a RO
 * 3. submit that RO to an LDP server that manages the RO
 *//*from   ww  w  .  ja va  2s .c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String requestURL = request.getRequestURL().toString();
    logger.debug("Received a POST request on '{}'", requestURL);

    Map<String, String[]> parameterMap = request.getParameterMap();

    RoRDFModel ro = new RoRDFModel(parameterMap);

    Model model = ro.process();

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    model.write(os, "TURTLE");
    String roString = os.toString();

    logger.debug("Form data is converted to RDF ... \n{}", roString);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/ldp4j/ldp-bc/");
    //HttpPost post = new HttpPost("http://linkeddata4.dia.fi.upm.es:8088/ldp4j/ldp-bc/");

    StringEntity body = new StringEntity(roString);
    body.setContentType("text/turtle");
    post.setEntity(body);

    HttpResponse ldpResponse = httpclient.execute(post);

    try {
        int statusCode = ldpResponse.getStatusLine().getStatusCode();
        logger.debug("LDP server responded with {} {}", statusCode,
                ldpResponse.getStatusLine().getReasonPhrase());

        if (statusCode == 201 && ldpResponse.getFirstHeader("Location") != null) {
            String location = ldpResponse.getFirstHeader("Location").getValue();
            logger.debug("URI of the newly created LDPR - {}", location);

            request.setAttribute("newURI", location);

            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/roCreated.jsp");
            dispatcher.forward(request, response);

        } else {
            logger.error("An error occurred while creating the RO. {} {}", statusCode,
                    ldpResponse.getStatusLine().getReasonPhrase());
        }

    } finally {
        post.releaseConnection();
    }

}

From source file:net.sourceforge.subsonic.backend.controller.RedirectionController.java

private String getFullRequestURL(HttpServletRequest request) throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder(request.getRequestURL());

    // For backwards compatibility; return query parameters in exact same sequence.
    if ("GET".equalsIgnoreCase(request.getMethod())) {
        if (request.getQueryString() != null) {
            builder.append("?").append(request.getQueryString());
        }//from  w ww.j a v  a 2 s  .  com
        return builder.toString();
    }

    builder.append("?");

    Enumeration<?> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = (String) paramNames.nextElement();
        String[] paramValues = request.getParameterValues(paramName);
        for (String paramValue : paramValues) {
            String p = URLEncoder.encode(paramValue, "UTF-8");
            builder.append(paramName).append("=").append(p).append("&");
        }
    }

    return builder.toString();
}

From source file:com.intel.podm.rest.HttpServletRequestValidator.java

public void validateServletRequest(HttpServletRequest httpServletRequest)
        throws HttpServletRequestValidationException {
    validateRequestLineLength(getRequestLine(httpServletRequest));
    validateUrlSyntax(httpServletRequest.getRequestURL().toString());
    validateUrlDecodingIsPossible(httpServletRequest.getRequestURL().toString());
}

From source file:com.sun.socialsite.web.filters.AnonymousAccessFilter.java

/**
 * If anonymous access not allowed then reject any request that does not
 * have either a SocialSite security token or an OAuth token.
 *///from w  ww  .  ja v a2s. com
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    log.debug("--- entering");
    if (allowAnonymous) {
        chain.doFilter(req, res);
    } else {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        log.debug(request.getMethod() + " " + request.getRequestURL().toString());
        log.debug("st=" + request.getParameter("st"));

        SecurityToken st = new AuthInfo(request).getSecurityToken();
        if (st != null && (st instanceof SocialSiteToken || st instanceof OAuthSecurityToken
                || st instanceof AssertedToken)) {
            chain.doFilter(req, res);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "No suitable security token found in request");
        }
    }
    log.debug("--- exiting");
}

From source file:com.redblackit.web.server.mvc.UrlChildLocation.java

/**
 * Constructor taking HttpServletRequest
 *
 * @param request (neither request not its requestURL may be null)
 *///from  ww  w .j a  v a  2 s  . co m
public UrlChildLocation(HttpServletRequest request) {
    Assert.notNull(request, "request must be non-null");
    StringBuffer rurlsb = request.getRequestURL();
    Assert.notNull(rurlsb, "request.getRequestURL must be non-null");
    this.requestUrl = rurlsb.toString();
}

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

/**
 * To hander GET fdp metadata request.// www. j  a  va 2 s.c o m
 * (Note:) The first value in the produces annotation is used as a fallback
 * value, for the request with the accept header value (* / *),
 * manually setting the contentType of the response is not working.
 * 
 * @param request   Http request
 * @param response  Http response   
 * @return  On success return FDP metadata
 */
@ApiOperation(value = "FDP metadata")
@RequestMapping(method = RequestMethod.GET, produces = { "text/turtle", "application/ld+json",
        "application/rdf+xml", "text/n3" })
public String getFDAMetaData(final HttpServletRequest request, HttpServletResponse response) {
    String responseBody;
    LOGGER.info("Request to get FDP metadata");
    LOGGER.info("GET : " + request.getRequestURL());
    String contentType = request.getHeader(HttpHeaders.ACCEPT);
    RDFFormat requesetedContentType = HttpHeadersUtils.getRequestedAcceptHeader(contentType);
    try {
        responseBody = fairMetaDataService.retrieveFDPMetaData(requesetedContentType);
        HttpHeadersUtils.set200ResponseHeaders(responseBody, response, requesetedContentType);
    } catch (FairMetadataServiceException ex) {
        responseBody = HttpHeadersUtils.set500ResponseHeaders(response, ex);
    }
    LoggerUtils.logRequest(LOGGER, request, response);
    return responseBody;
}

From source file:io.kamax.mxisd.controller.auth.v1.AuthController.java

private String resolveProxyUrl(HttpServletRequest req) {
    URI target = URI.create(req.getRequestURL().toString());
    URIBuilder builder = dns.transform(target);
    String urlToLogin = builder.toString();
    log.info("Proxy resolution: {} to {}", target.toString(), urlToLogin);
    return urlToLogin;
}

From source file:cc.kune.core.server.searcheable.SearchEngineServletFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException, DefaultException {
    if (filterConfig == null) {
        return;//from  www  . j a v a2  s.  c  o  m
    }

    if (request instanceof HttpServletRequest) {

        final HttpServletRequest httpReq = (HttpServletRequest) request;
        final StringBuffer url = httpReq.getRequestURL();

        final String queryString = httpReq.getQueryString();

        if ((queryString != null) && (queryString.contains(SiteParameters.ESCAPED_FRAGMENT_PARAMETER))) {
            if (!enabled) {
                final HttpServletResponse httpRes = (HttpServletResponse) response;
                httpRes.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Search Engine service disabled temporally");
                return;
            }
            // rewrite the URL back to the original #! version
            // remember to unescape any %XX characters
            final String urlWithEscapedFragment = request
                    .getParameter(SiteParameters.ESCAPED_FRAGMENT_PARAMETER);
            final String newUrl = url.append("?").append(queryString).toString()
                    .replaceFirst(SiteParameters.ESCAPED_FRAGMENT_PARAMETER, SiteParameters.NO_UA_CHECK)
                    .replaceFirst("/ws", "") + "#" + urlWithEscapedFragment;

            LOG.info("New url with hash: " + newUrl);

            final String page = "In development";
            // return the snapshot
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            response.getOutputStream().write(page.getBytes());
        } else {
            try {
                // not an _escaped_fragment_ URL, so move up the chain of
                // servlet (filters)
                chain.doFilter(request, response);
            } catch (final ServletException e) {
                LOG.error("Servlet exception caught: " + e);
            }
        }
    }
}

From source file:nl.mok.mastersofcode.spectatorclient.controllers.TeamController.java

@RequestMapping(method = RequestMethod.GET, value = "/{username}")
public ModelAndView showTeam(final HttpServletRequest request, @PathVariable String username) {
    ModelAndView mav = new ModelAndView();

    mav.addObject("page", new Object() {
        public String uri = "/spec/team";
        public String redirect = request.getRequestURL().toString();
    });/*w  w  w . ja v a 2  s  . c o  m*/

    mav.addObject("team", DataController.getTeamById(username).orElse(null));
    mav.addObject("currentCompetition", DataController.getCurrentCompetition());
    mav.addObject("currentRound", DataController.getCurrentRound());

    mav.setViewName("team.twig");

    return mav;
}

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

/**
 * Handle all null pointer exceptions./*from   w  w w . ja v  a2 s. co m*/
 *
 * @param req the req
 * @param exception the exception
 * @return the error info
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorInfo handleAllNullPointerExceptions(HttpServletRequest req, Exception exception) {
    logger.error("The data sent for processing had errors {}:", req.getRequestURL().toString(), exception);

    return new ErrorInfo(getCurrentTimestamp(), HttpStatus.BAD_REQUEST, req.getRequestURL().toString(),
            new Exception("An invalid value was sent or requested."));
}