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:com.sun.socialsite.web.filters.ThreadContextFilter.java

/**
 * Release SocialSite persistence session at end of request processing.
 *//*w ww. j  a  v  a 2 s.c o m*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    log.debug("Entered ThreadContextFilter");

    SocialSite socialsite = Factory.getSocialSite();

    log.debug(String.format("url=%s decoder=%s st=%s", request.getRequestURL(), decoder,
            request.getParameter("st")));
    if ((decoder != null) && (request.getParameter("st") != null)) {
        Map<String, String> m = Collections.singletonMap(SecurityTokenDecoder.SECURITY_TOKEN_NAME,
                request.getParameter("st"));
        try {
            final SocialSiteToken token = (SocialSiteToken) (decoder.createToken(m));
            log.debug(String.format("url=%s token=%s", request.getRequestURL(), token));
            if ((token != null) && (!socialsite.getURLStrategy().equals(token.getURLStrategy()))) {
                Object overrider = new Object() {
                    public URLStrategy getURLStrategy() {
                        log.debug(String.format("url=%s token=%s urlstrategy=%s", request.getRequestURL(),
                                token, token.getURLStrategy()));
                        return token.getURLStrategy();
                    }
                };
                SocialSite ss = (SocialSite) (ProxyUtil.getOverrideProxy(socialsite, overrider));
                log.debug(String.format("url=%s ss=%s", request.getRequestURL(), ss));
                Factory.setThreadLocalSocialSite(
                        (SocialSite) (ProxyUtil.getOverrideProxy(socialsite, overrider)));
                log.debug(String.format("url=%s Factory.getSocialSite=%s", request.getRequestURL(),
                        Factory.getSocialSite()));
            }
        } catch (SecurityTokenException e) {
            log.error("Failed to get security token", e);
        }
    }

    try {
        chain.doFilter(request, response);
    } finally {
        log.debug("Releasing SocialSite Session");
        if (Factory.isBootstrapped()) {
            Factory.setThreadLocalSocialSite(null);
            Factory.getSocialSite().release();
        }
    }

    log.debug("Exiting ThreadContextFilter");
}

From source file:gov.nih.nci.cabig.caaers.web.filters.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///w w w.ja  va2  s.  co  m
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        try {
            // Write the zipped body
            ResponseUtil.addGzipHeader(response);
            // see http://httpd.apache.org/docs/2.0/mod/mod_deflate.html or 'High Performance Web Sites' by Steve Souders.
            response.addHeader(VARY, "Accept-Encoding");
            response.addHeader(VARY, "User-Agent");
            response.setContentLength(compressedBytes.length);
        } catch (ResponseHeadersNotModifiableException e) {
            return;
        }

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

From source file:edu.duke.cabig.c3pr.web.admin.CreateOrganizationController.java

@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
    HealthcareSite hcs = null;//from   ww w .j a  va  2s  .co  m

    if (request.getParameter("primaryIdentifier") != null) {
        log.info(" Request URl  is:" + request.getRequestURL().toString());
        hcs = healthcareSiteDao.getByPrimaryIdentifier(request.getParameter("primaryIdentifier"));
        request.getSession().setAttribute(FLOW, EDIT_FLOW);
        log.info(" HCS's ID is:" + hcs.getId());
    } else {
        hcs = new LocalHealthcareSite();
        request.getSession().setAttribute(FLOW, SAVE_FLOW);
    }

    int cmSize = hcs.getContactMechanisms().size();
    if (cmSize == 0) {
        addContactsToSite(hcs);
    }
    if (cmSize == 1) {
        ContactMechanism contactMechanismPhone = new LocalContactMechanism();
        ContactMechanism contactMechanismFax = new LocalContactMechanism();
        contactMechanismPhone.setType(ContactMechanismType.PHONE);
        contactMechanismFax.setType(ContactMechanismType.Fax);
        hcs.addContactMechanism(contactMechanismPhone);
        hcs.addContactMechanism(contactMechanismFax);
    }
    if (cmSize == 2) {
        ContactMechanism contactMechanismFax = new LocalContactMechanism();
        contactMechanismFax.setType(ContactMechanismType.Fax);
        hcs.addContactMechanism(contactMechanismFax);
    }
    return hcs;
}

From source file:in.arun.faces.fo.pdf.FoOutputStream.java

@Override
public void close() throws IOException {
    if (closed) {
        throw new IOException("Stream has already been closed");
    }//from   www. j  a  v a  2  s . c o  m

    closed = true;
    PdfResult result = buildPdf(this);

    FacesContext context = FacesContext.getCurrentInstance();

    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

    response.reset();

    String fileName;
    if (null == (fileName = request.getParameter("output"))) {
        fileName = FilenameUtils.getBaseName(request.getRequestURL().toString());
    }

    fileName += ".pdf";

    response.setContentType(result.contentType);
    response.setContentLength(result.content.length);
    response.setHeader("content-disposition", "inline; FileName=\"" + fileName + "\"");

    OutputStream outputStream = response.getOutputStream();
    outputStream.write(result.content);
    outputStream.flush();

    context.responseComplete();
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Gets the exceuction.//from w w w  .  jav a  2  s.  co  m
 *
 * @param request the request
 * @param executionId the execution id
 * @return the exceuction
 * @throws Exception the exception
 */
@RequestMapping(value = "executor/execution/{executionId}", method = RequestMethod.GET)
public Object getExceuction(HttpServletRequest request, @PathVariable String executionId) throws Exception {

    String requestUrl = request.getRequestURL().toString();
    requestUrl = StringUtils.substringBeforeLast(requestUrl, "/execution/") + "/execution/{id}/{resource}";

    UriTemplate template = new UriTemplate(requestUrl);

    Execution execution = new Execution(this.fileSystemResolver.getExecutionInfo(executionId), template);

    String xml = xmlProcessor.executionToXml(execution);

    return this.buildResponse(request, "executor/execution", execution, xml);
}

From source file:com.bitium.confluence.saml.SAMLContext.java

public SAMLMessageContext createSamlMessageContext(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, MetadataProviderException {
    SAMLMessageContext context = messageContextProvider.getLocalAndPeerEntity(request, response);

    SPSSODescriptor spDescriptor = (SPSSODescriptor) context.getLocalEntityRoleMetadata();

    String responseURL = request.getRequestURL().toString();
    spDescriptor.getDefaultAssertionConsumerService().setResponseLocation(responseURL);
    for (AssertionConsumerService service : spDescriptor.getAssertionConsumerServices()) {
        service.setResponseLocation(responseURL);
    }// w  w w.j a v  a 2s .  c  om

    spDescriptor.setAuthnRequestsSigned(false);
    context.setCommunicationProfileId(SAMLConstants.SAML2_WEBSSO_PROFILE_URI);

    return context;
}

From source file:fi.aluesarjat.prototype.ContextAccessServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;//from  w w w .jav  a 2 s .c o  m
    }

    String context = request.getRequestURL().toString();
    RDFConnection connection = repository.openConnection();
    try {
        SPARQLQuery query = connection.createQuery(QueryLanguage.SPARQL,
                "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH ?context { ?s ?p ?o } }");
        query.setBinding("context", new UID(context));

        String contentType = null;
        String format = request.getParameter("format");
        if ("turtle".equals(format)) {
            contentType = Format.TURTLE.getMimetype();
        } else if ("ntriples".equals(format)) {
            contentType = Format.NTRIPLES.getMimetype();
        } else {
            contentType = getAcceptedType(request, Format.RDFXML);
        }
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setContentType(contentType);
        query.streamTriples(response.getWriter(), contentType);
    } finally {
        connection.close();
    }
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///ww w .  j  a v a  2s  . c  o m
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        // Write the zipped body
        ResponseUtil.addGzipHeader(response);
        response.setContentLength(compressedBytes.length);

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

From source file:it.smartcommunitylab.aac.controller.GlobalDefaultExceptionHandler.java

public ModelAndView resolveException(HttpServletRequest aReq, HttpServletResponse aRes, Object aHandler,
        Exception anExc) {//from   ww  w  .  jav  a 2  s .co m
    // hack. should be done better in configuration   
    if ("/oauth/token".equals(aReq.getServletPath())) {
        return null;
    }
    // Otherwise setup and send the user to a default error-view.
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", anExc);
    mav.addObject("url", aReq.getRequestURL());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    logger.error("Global erro handler", anExc);
    return mav;
}

From source file:com.redhat.rhn.frontend.action.user.UserPrefSetupAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {//from  w  w w.j ava  2 s. c  o  m
    DynaActionForm form = (DynaActionForm) formIn;
    RequestContext requestContext = new RequestContext(request);
    Long uid = requestContext.getParamAsLong("uid");
    //UserPreferences under /rhn/users needs parameter, but /rhn/account does not
    if (request.getRequestURL().toString().indexOf("/rhn/users/") != -1 && uid == null) {
        throw new BadParameterException("Invalid [null] value for parameter uid");
    }

    User user = UserManager.lookupUser(requestContext.getCurrentUser(), uid);
    request.setAttribute(RhnHelper.TARGET_USER, user);
    if (user == null) {
        user = requestContext.getCurrentUser();
    }

    form.set("uid", user.getId());
    form.set("emailNotif", BooleanUtils.toBooleanObject(user.getEmailNotify()));

    form.set("pagesize", new Integer(user.getPageSize()));
    form.set("csvSeparator", user.getCsvSeparator());

    setupTasks(form, user);
    request.setAttribute("pagesizes", getPageSizes());

    return mapping.findForward(RhnHelper.DEFAULT_FORWARD);
}