Example usage for javax.servlet.http HttpServletRequest getServerName

List of usage examples for javax.servlet.http HttpServletRequest getServerName

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServerName.

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

From source file:flex.messaging.services.http.proxy.ProxyContextFilter.java

protected void setupTarget(ProxyContext context) {
    Target target = context.getTarget();
    String source = context.getUrl();
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

    try {//from w ww.  j  a  v a2 s .  c  o  m
        target.setUrl(new URL(source));
    } catch (MalformedURLException e) {
        try {
            //[Pete] Enhancement Req. 80172 - relative URLs from webroot (not
            //       webapp context root)
            if (clientRequest != null) {
                String baseurl = "http" + (clientRequest.isSecure() ? "s" : "") + "://"
                        + clientRequest.getServerName() + ":" + clientRequest.getServerPort();

                target.setUrl(new URL(baseurl + source));
            } else {
                ProxyException pe = new ProxyException();
                pe.setMessage(RELATIVE_NOT_SUPPORTED, new Object[] { source });
                throw pe;
            }
        } catch (MalformedURLException ex) {
            target.setUrl(null);
        }
    }

    if (target.getUrl() == null) {
        ProxyException pe = new ProxyException();
        pe.setMessage(INVALID_TARGET, new Object[] { source });
        throw pe;
    }

    target.setHTTPS(target.getUrl().getProtocol().equalsIgnoreCase("https"));
    target.setEncodedPath(target.getUrl().getPath());
    String queryStr = target.getUrl().getQuery();
    if (queryStr != null) {
        target.setEncodedPath(target.getEncodedPath() + ("?" + queryStr));
    }
    try {
        target.setEncodedPath(URIUtil.encodePathQuery(target.getEncodedPath()));
    } catch (URIException e) {
        // exception is thrown if the default charset is not supported.
        // proceed with the provided URL.
    }

    target.setHostConfig(new HostConfiguration());
    String targetHost = target.getUrl().getHost();
    int targetPort = target.getUrl().getPort();

    // Check for a custom protocol
    Protocol customProtocol = context.getProtocol();
    if (customProtocol != null) {
        target.getHostConfig().setHost(targetHost, targetPort, customProtocol);
    } else if (target.isHTTPS() && context.allowLaxSSL()) {
        target.getHostConfig().setHost(targetHost, targetPort, myhttps);
    } else {
        String targetProtocol = target.getUrl().getProtocol();
        target.getHostConfig().setHost(targetHost, targetPort, targetProtocol);
    }

    if (context.getConnectionManager() != null) {
        context.setHttpClient(new HttpClient(context.getConnectionManager()));
    } else {
        context.setHttpClient(new HttpClient());
    }

    // Determine if target domain matches this proxy's domain and port
    boolean localDomain = false;
    boolean localPort = false;
    if (clientRequest != null) {
        String proxyDomain = clientRequest.getServerName().contains(STRING_LOCALHOST) ? getResolvedLocalhost()
                : clientRequest.getServerName();
        String resolvedTargetHost = targetHost.contains(STRING_LOCALHOST) ? getResolvedLocalhost() : targetHost;
        if (proxyDomain.equalsIgnoreCase(resolvedTargetHost)) {
            localDomain = true;
            int proxyPort = clientRequest.getServerPort();
            localPort = proxyPort == targetPort;
        }
    }
    context.setLocalDomain(localDomain);
    context.setLocalPort(localPort);
}

From source file:org.sample.nonblocking.TestClient.java

/**
 * Processes requests for both HTTP//from w w w  . j av  a  2 s . co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestClient</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestClient at " + request.getContextPath() + "</h1>");

        String path = "http://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/ReadTestServlet";
        out.println("Invoking the endpoint: " + path + "<br>");
        out.flush();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setChunkedStreamingMode(2);
        conn.setDoOutput(true);
        conn.connect();
        try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()))) {
            out.println("Sending data ..." + "<br>");
            out.flush();
            output.write("Hello");
            output.flush();
            out.println("Sleeping ..." + "<br>");
            out.flush();
            Thread.sleep(5000);
            out.println("Sending more data ..." + "<br>");
            out.flush();
            output.write("World");
            output.flush();
            output.close();
        }
        out.println("<br><br>Check GlassFish server.log");
        out.println("</body>");
        out.println("</html>");
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(ReadTestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cn.vlabs.duckling.vwb.VWBDriverServlet.java

private boolean requireRedirect(HttpServletRequest request, URLParser parser, int siteId) {
    DomainNameService domainService = container.getDomainService();
    if (domainService.getSiteDefaultDomain(siteId) == null) {
        // use use siteid identifier
        if (StringUtils.isBlank(parser.getSiteId())) {
            return true;
        }/*from  w w w . jav  a 2  s .  c o m*/
        if (!StringUtils.equals(domainService.getDefaultDomain(), request.getServerName())) {
            return true;
        }
    } else {
        // use domain identifier.
        if (!StringUtils.isBlank(parser.getSiteId())) {
            return true;
        }
        if (!StringUtils.equalsIgnoreCase(domainService.getSiteDefaultDomain(siteId),
                request.getServerName())) {
            return true;
        }
    }
    return false;
}

From source file:br.com.sg.security.SgLoginUrlAuthenticationEntryPoint.java

protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) {

    String loginForm = determineUrlToUseForThisRequest(request, response, authException);
    Integer serverPort = portResolver.getServerPort(request);
    String scheme = request.getScheme();

    RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();

    urlBuilder.setScheme(scheme);//from w  ww.  j a  v  a  2  s  .co  m
    urlBuilder.setServerName(request.getServerName());
    urlBuilder.setPort(serverPort);
    urlBuilder.setContextPath(request.getContextPath());
    urlBuilder.setPathInfo(loginForm);

    if (forceHttps && "http".equals(scheme)) {
        Integer httpsPort = portMapper.lookupHttpsPort(new Integer(serverPort));

        if (httpsPort != null) {
            // Overwrite scheme and port in the redirect URL
            urlBuilder.setScheme("https");
            urlBuilder.setPort(httpsPort.intValue());
        } else {
            logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);
        }

    }

    return urlBuilder.getUrl();
}

From source file:com.searchbox.framework.web.Auth0LoginController.java

@RequestMapping("/index")
protected String login(final Map<String, Object> model, final HttpServletRequest req) {
    logger.info("Performing login");
    detectError(model);// ww  w . ja va2s. c o  m
    // add a Nonce value to session storage
    NonceUtils.addNonceToStorage(req);
    model.put("clientId", appConfig.getClientId());
    model.put("clientDomain", appConfig.getDomain());
    model.put("loginCallback", appConfig.getLoginCallback());
    model.put("state", SessionUtils.getState(req));

    int port = req.getServerPort();
    String url;
    if (port == 80) {
        url = String.format("%s://%s/", req.getScheme(), req.getServerName());
    } else {
        url = String.format("%s://%s:%d/", req.getScheme(), req.getServerName(), req.getServerPort());
    }
    String redirectUrl = appConfig.getIssuer() + "authorize?" + "response_type=code&scope=openid%20profile&"
            + "client_id=" + appConfig.getClientId() + "&" + "state=" + SessionUtils.getState(req)
            + "&redirect_uri=" + url + "callback";
    return "redirect:" + redirectUrl;
}

From source file:com.identityconcepts.shibboleth.WSFedLoginHandler.java

/**
 * return URL to which redirect will be done
 * depending on the X509 handler configuration,
 * a full URL will be used or a path in the web app
 *
 * @param  request  HTTPServletRequest//  ww  w.  j  a v a2  s.  co m
 * @return          URL for redirection
 */
private String getRedirectURL(HttpServletRequest request, String url) {
    URLBuilder urlBuilder = null;
    // if URL configured
    if (url.startsWith("http")) {
        urlBuilder = new URLBuilder(url);
    } else {
        // if path configured
        log.debug("No URL configured in loginPageURL: {}", url);

        StringBuilder pathBuilder = new StringBuilder();
        urlBuilder = new URLBuilder();
        urlBuilder.setScheme(request.getScheme());
        urlBuilder.setHost(request.getServerName());
        // set port if not standard port
        if (!(request.getScheme().equals("http")) || (request.getScheme().equals("https"))) {
            urlBuilder.setPort(request.getServerPort());
        }

        pathBuilder.append(request.getContextPath());
        if (!loginPageURL.startsWith("/")) {
            pathBuilder.append("/");
        }
        pathBuilder.append(url);

        urlBuilder.setPath(pathBuilder.toString());
    }
    return urlBuilder.buildURL();
}

From source file:com.meltmedia.cadmium.servlets.MaintenanceFilter.java

@Override
public void doFilter(HttpServletRequest httpReq, HttpServletResponse httpRes, FilterChain chain)
        throws IOException, ServletException {
    try {//from w w w.j a v a 2s  . c o m
        String contextPath = httpReq.getContextPath();
        String uri = httpReq.getRequestURI();
        if (contextPath != null && contextPath.trim().length() > 0 && uri.startsWith(contextPath)) {
            uri = uri.substring(contextPath.length());
        }
        if (!on || (ignorePath != null && uri.startsWith(ignorePath))) {
            logger.trace("Serving request server:{}, uri:{}", httpReq.getServerName(), uri);
            chain.doFilter(httpReq, httpRes);
            return;
        }

        httpRes.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        httpRes.setContentType(MediaType.TEXT_HTML);
        InputStream in = null;
        InputStreamReader reader = null;
        try {
            in = MaintenanceFilter.class.getResourceAsStream("/maintenance.html");
            if (in == null) {
                in = MaintenanceFilter.class.getResourceAsStream("./maintenance.html");
            }
            reader = new InputStreamReader(in, "UTF-8");
            IOUtils.copy(reader, httpRes.getWriter());
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(httpRes.getWriter());
        }
    } catch (IOException ioe) {
        logger.trace("Failed in maint filter.", ioe);
        throw ioe;
    } catch (ServletException se) {
        logger.trace("Failed in maint filter.", se);
        throw se;
    } catch (Throwable t) {
        logger.trace("Failed in maint filter.", t);
        throw new ServletException(t);
    }
}

From source file:org.hdiv.urlProcessor.AbstractUrlProcessor.java

/**
 * Detects if the url points to this application
 * //from   ww  w .ja  v  a  2 s  . co  m
 * @param request
 *            {@link HttpServletRequest} object
 * @param url
 *            request url
 * @param urlData
 *            url data
 * @return is internal?
 */
protected boolean isInternalUrl(HttpServletRequest request, String url, UrlData urlData) {

    if (urlData.getServer() != null) {
        // URL is absolute: http://...

        String serverName = request.getServerName();
        if (!urlData.getServer().contains(serverName)) {
            // http://www.google.com
            return false;
        }

        if (url.startsWith(request.getContextPath() + "/") || url.equals(request.getContextPath())) {
            // http://localhost:8080/APP/... or
            // http://localhost:8080/APP
            return true;
        }
        // http://localhost:8080/anotherApplication... or
        return false;

    } else {
        if (url.startsWith(request.getContextPath() + "/") || url.equals(request.getContextPath())) {
            // url of type /APP/... or /APP
            return true;
        } else if (url.startsWith("/")) {
            // url of type /anotherApplication/...
            return false;
        } else {
            // url of type section/action...
            return true;
        }
    }
}

From source file:com.janrain.backplane.server.Backplane1Controller.java

private void aniLogNewChannel(HttpServletRequest request, String referer, String version, String bus,
        String channel) {/*from ww  w .  j a v a  2 s .co  m*/
    if (!anilogger.isEnabled()) {
        return;
    }

    String channelId = "https://" + request.getServerName() + "/" + version + "/bus/" + bus + "/channel/"
            + channel;
    String siteHost = (referer != null) ? ServletUtil.getHostFromUrl(referer) : null;
    Map<String, Object> aniEvent = new HashMap<String, Object>();
    aniEvent.put("channel_id", channelId);
    aniEvent.put("bus", bus);
    aniEvent.put("version", version);
    aniEvent.put("site_host", siteHost);

    aniLog("new_channel", aniEvent);
}

From source file:eu.supersede.fe.rest.NotificationRest.java

@RequestMapping("")
public List<Notification> getByUserId(Authentication authentication, HttpServletRequest request,
        @RequestParam(defaultValue = "true") Boolean toRead) {
    String scheme;//  www. j a v  a 2s . c om
    String host;
    String port;

    if (request.getHeader("x-forwarded-proto") != null || request.getHeader("x-forwarded-host") != null
            || request.getHeader("x-forwarded-port") != null) {
        scheme = request.getHeader("x-forwarded-proto") != null ? request.getHeader("x-forwarded-proto")
                : "http";
        host = request.getHeader("x-forwarded-host") != null ? request.getHeader("x-forwarded-host")
                : request.getServerName();
        port = request.getHeader("x-forwarded-port") != null ? request.getHeader("x-forwarded-port") : null;
    } else {
        scheme = request.getScheme();
        host = request.getServerName();
        port = new Integer(request.getServerPort()).toString();
    }

    String baseUrl = port != null ? scheme + "://" + host + ":" + port + "/#/" : scheme + "://" + host + "/#/";

    DatabaseUser currentUser = (DatabaseUser) authentication.getPrincipal();
    User u = users.getOne(currentUser.getUserId());
    List<Notification> ns;

    if (toRead) {
        ns = notifications.findByUserAndReadOrderByCreationTimeDesc(u, !toRead);
    } else {
        ns = notifications.findByUserOrderByCreationTimeDesc(u);
    }

    for (Notification n : ns) {
        if (n.getLink() != null && !n.getLink().equals("")) {
            try {
                URI uri = new URI(n.getLink());

                if (!uri.isAbsolute()) {
                    n.setLink(baseUrl + n.getLink());
                }
            } catch (URISyntaxException e) {
                log.debug("Error inside link: " + e.getMessage());
            }
        }
    }

    return ns;
}