Example usage for javax.servlet ServletRequest getScheme

List of usage examples for javax.servlet ServletRequest getScheme

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getScheme.

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint.java

public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = portResolver.getServerPort(request);
    String contextPath = req.getContextPath();

    boolean inHttp = "http".equals(scheme.toLowerCase());
    boolean inHttps = "https".equals(scheme.toLowerCase());

    boolean includePort = true;

    String redirectUrl = null;//from ww  w . j  a v a 2  s  . c o m
    boolean doForceHttps = false;
    Integer httpsPort = null;

    if (inHttp && (serverPort == 80)) {
        includePort = false;
    } else if (inHttps && (serverPort == 443)) {
        includePort = false;
    }

    if (forceHttps && inHttp) {
        httpsPort = (Integer) portMapper.lookupHttpsPort(new Integer(serverPort));

        if (httpsPort != null) {
            doForceHttps = true;
            if (httpsPort.intValue() == 443) {
                includePort = false;
            } else {
                includePort = true;
            }
        }

    }

    String loginForm = determineUrlToUseForThisRequest(req, resp, authException);

    if (serverSideRedirect) {

        if (doForceHttps) {

            // before doing server side redirect, we need to do client
            // redirect to https.

            String servletPath = req.getServletPath();
            String pathInfo = req.getPathInfo();
            String query = req.getQueryString();

            redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath
                    + servletPath + (pathInfo == null ? "" : pathInfo) + (query == null ? "" : "?" + query);

        } else {

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            RequestDispatcher dispatcher = req.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;

        }

    } else {

        if (doForceHttps) {

            redirectUrl = "https://" + serverName + ((includePort) ? (":" + httpsPort) : "") + contextPath
                    + loginForm;

        } else {

            redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath
                    + loginForm;

        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to: " + redirectUrl);
    }

    ((HttpServletResponse) response)
            .sendRedirect(((HttpServletResponse) response).encodeRedirectURL(redirectUrl));
}

From source file:pt.webdetails.cdv.api.CdvApi.java

private String getRoot(ServletRequest wrapper) {
    return wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort();
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

private String getRoot() {

    ServletRequest wrapper = getRequest();
    String root = wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort();

    return root;/*w  w w  .ja  v  a2 s .  c  om*/
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC)
public void home(OutputStream out) throws IOException {

    IParameterProvider requestParams = getRequestParameters();
    // IParameterProvider pathParams = getPathParameters();
    ServletRequest wrapper = getRequest();
    String root = wrapper.getScheme() + "://" + wrapper.getServerName() + ":" + wrapper.getServerPort();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("solution", "system");
    params.put("path", "cfr/presentation/");
    params.put("file", "cfr.wcdf");
    params.put("absolute", "false");
    params.put("inferScheme", "false");
    params.put("root", root);

    // add request parameters
    PluginUtils.copyParametersFromProvider(params, WrapperUtils.wrapParamProvider(requestParams));

    if (requestParams.hasParameter("mode")
            && requestParams.getStringParameter("mode", "Render").equals("edit")) {

        // Send this to CDE

        redirectToCdeEditor(out, params);
        return;//from  www  . j  a  v a  2s  . co m
    }

    InterPluginCall pluginCall = new InterPluginCall(InterPluginCall.CDE, "Render", params);
    pluginCall.setResponse(getResponse());
    pluginCall.setRequest(getRequest());
    pluginCall.setOutputStream(out);
    pluginCall.run();

}

From source file:org.parancoe.web.tag.MarkPositionTag.java

@Override
protected final int doStartTagInternal() throws JspException, IOException {
    final HttpSession session = pageContext.getSession();
    ServletRequest request = pageContext.getRequest();
    final RequestContext requestContext = this.getRequestContext();
    final String uri = requestContext.getRequestUri();
    String contextPath = requestContext.getContextPath();
    final String queryString = requestContext.getQueryString();
    String url = "";
    if (uri.startsWith(contextPath)) {
        url = uri.substring(contextPath.length());
    } else {// w w w  . j  ava 2s.c  om
        url = uri;
    }
    if (!StringUtils.isBlank(queryString)) {
        url = url + "?" + queryString;
    }
    if (useFullUri) {
        String port = "";
        if (request.getServerPort() != 80) {
            port = ":" + request.getServerPort();
        }
        url = request.getScheme() + "://" + request.getServerName() + port + requestContext.getContextPath()
                + url;
    }
    MarkPositionHelper.markPosition(session, pathId, url);
    return SKIP_BODY;
}

From source file:net.sf.j2ep.ProxyFilter.java

/**
 * Implementation of a reverse-proxy. All request go through here. This is
 * the main class where are handling starts.
 * //from w  ww .  ja  v  a2  s  . c o m
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    //httpRequest.setCharacterEncoding("UTF-8");
    //httpResponse.setCharacterEncoding("UTF-8");
    Server server = (Server) httpRequest.getAttribute("proxyServer");
    if (server == null) {
        server = serverChain.evaluate(httpRequest);
    }

    if (server == null) {
        filterChain.doFilter(request, response);
    } else {
        String uri = server.getRule().process(getURI(httpRequest));
        String url = request.getScheme() + "://" + server.getDomainName() + server.getPath() + uri;
        log.debug("Connecting to " + url);

        ResponseHandler responseHandler = null;

        try {
            httpRequest = server.preExecute(httpRequest);
            responseHandler = executeRequest(httpRequest, url);
            httpResponse = server.postExecute(httpResponse);

            responseHandler.process(httpResponse);
        } catch (HttpException e) {
            log.error("Problem while connecting to server", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            server.setConnectionExceptionRecieved(e);
        } catch (UnknownHostException e) {
            log.error("Could not connection to the host specified", e);
            httpResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            server.setConnectionExceptionRecieved(e);
        } catch (IOException e) {
            log.error("Problem probably with the input being send, either with a Header or the Stream", e);
            httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (MethodNotAllowedException e) {
            log.error("Incoming method could not be handled", e);
            httpResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            httpResponse.setHeader("Allow", e.getAllowedMethods());
        } finally {
            if (responseHandler != null) {
                responseHandler.close();
            }
        }
    }
}

From source file:org.beangle.security.web.auth.LoginUrlEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *//*from  w  ww  .  ja  va2  s.  c o m*/
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String redirectUrl = null;
    if (serverSideRedirect) {
        String loginForm = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);
        logger.debug("Server side forward to: {}", loginForm);
        RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(loginForm);
        dispatcher.forward(request, response);
        return;
    } else {
        // redirect to login page. Use https if forceHttps true
        redirectUrl = determineUrlToUseForThisRequest(httpRequest, httpResponse, authException);
    }
    if (!("XMLHttpRequest".equals(httpRequest.getHeader("x-requested-with"))
            || StringUtils.isNotEmpty(httpRequest.getParameter("x-requested-with")))) {
        String backurl = new UrlBuilder(httpRequest.getContextPath()).scheme(request.getScheme())
                .serverName(request.getServerName()).port(request.getServerPort())
                .servletPath(httpRequest.getServletPath()).queryString(httpRequest.getQueryString()).buildUrl();
        redirectUrl += "?backurl=" + URLEncoder.encode(backurl);
    }
    //      httpRequest.getSession().setAttribute("backurl", backurl);
    //      httpRequest.getSession().setAttribute("backurltime", System.currentTimeMillis());
    RedirectUtils.sendRedirect(httpRequest, httpResponse, redirectUrl);
}

From source file:org.jahia.services.content.JCRStoreProvider.java

public String getAbsoluteContextPath(ServletRequest request) {
    StringBuilder serverUrlBuffer = new StringBuilder(request.getScheme());
    serverUrlBuffer.append("://");
    serverUrlBuffer.append(request.getServerName());
    if (request.getServerPort() != 80 && request.getServerPort() != 443) {
        serverUrlBuffer.append(":");
        serverUrlBuffer.append(request.getServerPort());
    }/*from w  w  w . j a  v a2  s.com*/
    return serverUrlBuffer.toString();
}

From source file:org.ambraproject.web.VirtualJournalContextFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    final Collection<String> virtualJournals = configuration.getList(CONF_VIRTUALJOURNALS_JOURNALS);

    String defaultJournal = configuration.getString(CONF_VIRTUALJOURNALS_DEFAULT);

    // need to do <rule> based processing
    String journalName = findMatchingVirtualJournal(configuration, (HttpServletRequest) request);

    if (journalName != null) {
        if (log.isTraceEnabled()) {
            log.trace("journal from rules: journal = \"" + journalName + "\"");
        }/* w ww.  j  a v a 2 s.  co  m*/
    } else {
        // was a simple config <default> specified?

        journalName = defaultJournal;

        if (log.isTraceEnabled()) {
            log.trace("journal from defaults: journal = \"" + journalName + "\"");
        }
    }

    // empty if default not set
    if (journalName == null) {
        journalName = "";

        if (log.isTraceEnabled()) {
            log.trace("Default journal not set");
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("journal = \"" + journalName + "\" for " + ((HttpServletRequest) request).getRequestURL());
    }

    // put virtualJournal context in the ServletRequest for webapp to use
    request.setAttribute(VirtualJournalContext.PUB_VIRTUALJOURNAL_CONTEXT,
            new VirtualJournalContext(journalName, defaultJournal, request.getScheme(), request.getServerPort(),
                    request.getServerName(), ((HttpServletRequest) request).getContextPath(), virtualJournals));

    /*
     * Establish a "Nested Diagnostic Context" for logging, e.g. prefix log entries w/journal name
     * http://logging.apache.org/log4j/docs/api/org/apache/log4j/NDC.html
     */
    NDC.push(journalName);

    try {
        // continue the Filter chain ...
        filterChain.doFilter(request, response);
    } finally {
        // cleanup "Nested Diagnostic Context" for logging
        NDC.pop();
        NDC.remove(); // TODO: appropriate place to cleanup for Thread?
    }
}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from  w  ww  .  j a  v a2 s  . c  om
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}