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:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/*w w w . j  a v  a 2s.c  o m*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:be.fedict.eid.idp.sp.protocol.ws_federation.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}// ww  w .j av a 2  s . co  m
 */
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");

    String idpDestination;
    String spDestination;
    String context;
    String language;
    String spRealm;

    AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
    if (null != service) {
        idpDestination = service.getIdPDestination();
        context = service.getContext(request.getParameterMap());
        spDestination = service.getSPDestination();
        language = service.getLanguage();
        spRealm = service.getSPRealm();
    } else {
        idpDestination = this.idpDestination;
        context = null;
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
        language = this.language;
        spRealm = this.spRealm;
    }

    String targetUrl;
    if (null == spRealm) {
        targetUrl = idpDestination + "?wa=wsignin1.0" + "&wtrealm=" + spDestination;
    } else {
        targetUrl = idpDestination + "?wa=wsignin1.0" + "&wtrealm=" + spRealm + "&wreply=" + spDestination;
    }

    if (null != language && !language.trim().isEmpty()) {
        targetUrl += "&language=" + language;
    }
    if (null != context && !context.trim().isEmpty()) {
        targetUrl += "&wctx=" + context;
    }

    LOG.debug("targetURL: " + targetUrl);
    response.sendRedirect(targetUrl);

    // save state on session
    if (null == spRealm) {
        setRecipient(spDestination, request.getSession());
    } else {
        setRecipient(spRealm, request.getSession());
    }
    setContext(context, request.getSession());
}

From source file:com.janrain.backplane2.server.Backplane2Controller.java

/**
 * Handle dynamic discovery of this server's registration endpoint
 * @return/*  w w w. j  a  v a 2 s  . co m*/
 */
@RequestMapping(value = "/.well-known/host-meta", method = { RequestMethod.GET })
public ModelAndView xrds(HttpServletRequest request, HttpServletResponse response) {

    ModelAndView view = new ModelAndView("xrd");
    view.addObject("host", "http://" + request.getServerName());
    view.addObject("secureHost", "https://" + request.getServerName());
    return view;
}

From source file:fr.insalyon.creatis.vip.core.server.rpc.ConfigurationServiceImpl.java

private URL getBaseURL() throws MalformedURLException {
    URL url = null;//from   ww w.ja  v  a  2s .  c o m
    HttpServletRequest request = this.getThreadLocalRequest();
    if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) {
        url = new URL(request.getScheme() + "://" + request.getServerName() + request.getContextPath());
    } else {
        url = new URL(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath());
    }
    return url;
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP//from ww w  . ja  v a 2 s . c  o 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 req, HttpServletResponse res)
        throws ServletException, IOException {
    res.setContentType("text/plain;charset=gbk");

    res.setContentType("text/html; charset=utf-8");
    PrintWriter pw = res.getWriter();
    try {
        //initialize the prefix url
        if (prefix_url == null) {
            //                String hostname = req.getServerName ();
            //                int port = req.getServerPort ();
            //                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            //updated by Ziheng - on 8/27/2015
            //This method should be used everywhere.
            int num = req.getRequestURI().indexOf("/PACS");
            String prefix = req.getRequestURI().substring(0, num + "/PACS".length()); //in case there is something before PACS
            prefix_url = req.getScheme() + "://" + req.getServerName()
                    + ("http".equals(req.getScheme()) && req.getServerPort() == 80
                            || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? ""
                                    : ":" + req.getServerPort())
                    + prefix + "/" + relativePath + "/";
        }
        pw.println("<!DOCTYPE html>");
        pw.println("<html>");
        String head = "<head>" + "<title>File Uploading Response</title>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
                + "<script type=\"text/javascript\" src=\"js/TaskGridTool.js\"></script>" + "</head>";
        pw.println(head);
        pw.println("<body>");

        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        // threshold  2M 
        //extend to 2M - updated by ziheng - 9/25/2014
        diskFactory.setSizeThreshold(2 * 1024);
        // repository 
        diskFactory.setRepository(new File(tempPath));

        ServletFileUpload upload = new ServletFileUpload(diskFactory);
        // 2M
        upload.setSizeMax(2 * 1024 * 1024);
        // HTTP
        List fileItems = upload.parseRequest(req);
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item, pw);
            } else {
                processUploadFile(item, pw);
            }
        } // end while()
          //add some buttons for further process
        pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
        pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
        pw.println("</body>");
        pw.println("</html>");
    } catch (Exception e) {
        e.printStackTrace();
        pw.println("ERR:" + e.getClass().getName() + ":" + e.getLocalizedMessage());
    } finally {
        pw.flush();
        pw.close();
    }
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }//  w w  w.ja v a 2  s  .c om
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}

From source file:net.sf.j2ep.requesthandlers.RequestHandlerBase.java

/**
 * Will write the proxy specific headers such as Via and x-forwarded-for.
 * //from  w ww .  ja v a  2s.c o  m
 * @param method Method to write the headers to
 * @param request The incoming request, will need to get virtual host.
 * @throws HttpException 
 */
private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    String serverHostName = "jEasyExtensibleProxy";
    try {
        serverHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
    }

    String originalVia = request.getHeader("via");
    StringBuffer via = new StringBuffer("");
    if (originalVia != null) {
        if (originalVia.indexOf(serverHostName) != -1) {
            log.error("This proxy has already handled the request, will abort.");
            throw new HttpException("Request has a cyclic dependency on this proxy.");
        }
        via.append(originalVia).append(", ");
    }
    via.append(request.getProtocol()).append(" ").append(serverHostName);

    method.setRequestHeader("via", via.toString());
    method.setRequestHeader("x-forwarded-for", request.getRemoteAddr());
    method.setRequestHeader("x-forwarded-host", request.getServerName());
    method.setRequestHeader("x-forwarded-server", serverHostName);

    method.setRequestHeader("accept-encoding", "");
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationResponseServlet.java

@SuppressWarnings("unchecked")
private void doIdRes(HttpServletRequest request, HttpServletResponse response)
        throws MessageException, DiscoveryException, AssociationException, IOException, ServletException {
    LOG.debug("id_res");
    LOG.debug("request URL: " + request.getRequestURL());

    // force UTF-8 encoding
    try {/*from   w ww.j  av a 2  s  .com*/
        request.setCharacterEncoding("UTF8");
        response.setCharacterEncoding("UTF8");
    } catch (UnsupportedEncodingException e) {
        throw new MessageException(e);
    }

    ParameterList parameterList = new ParameterList(request.getParameterMap());
    DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute("openid-disc");
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request URI: " + request.getRequestURI());
    String receivingUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getRequestURI();
    String queryString = request.getQueryString();
    if (queryString != null && queryString.length() > 0) {
        receivingUrl += "?" + queryString;
    }
    LOG.debug("receiving url: " + receivingUrl);
    ConsumerManager consumerManager = AuthenticationRequestServlet.getConsumerManager(request);
    VerificationResult verificationResult = consumerManager.verify(receivingUrl, parameterList, discovered);
    Identifier identifier = verificationResult.getVerifiedId();
    if (null != identifier) {

        Date authenticationTime = null;
        String userId = identifier.getIdentifier();
        List<String> authnPolicies = new LinkedList<String>();
        Map<String, Object> attributeMap = new HashMap<String, Object>();
        LOG.debug("userId: " + userId);
        Message authResponse = verificationResult.getAuthResponse();

        // verify return_to nonce
        AuthSuccess authResp = AuthSuccess.createAuthSuccess(parameterList);

        String returnTo = authResp.getReturnTo();
        String requestReturnTo = (String) request.getSession()
                .getAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);
        if (null == returnTo || null == requestReturnTo) {
            showErrorPage("Insufficient args for validation of " + " \"openid.return_to\".", null, request,
                    response);
            return;
        }
        if (!consumerManager.verifyReturnTo(requestReturnTo, authResp)) {
            showErrorPage("Invalid \"return_to\" in response!", null, request, response);
            return;
        }
        // cleanup
        request.getSession().removeAttribute(AuthenticationRequestServlet.RETURN_TO_SESSION_ATTRIBUTE);

        // AX
        if (authResponse.hasExtension(AxMessage.OPENID_NS_AX)) {

            MessageExtension messageExtension = authResponse.getExtension(AxMessage.OPENID_NS_AX);
            if (messageExtension instanceof FetchResponse) {

                FetchResponse fetchResponse = (FetchResponse) messageExtension;

                Map<String, String> attributeTypes = fetchResponse.getAttributeTypes();
                for (Map.Entry<String, String> entry : attributeTypes.entrySet()) {
                    attributeMap.put(entry.getValue(), fetchResponse.getAttributeValue(entry.getKey()));
                }

            }

        }

        // PAPE
        if (authResponse.hasExtension(PapeResponse.OPENID_NS_PAPE)) {

            MessageExtension messageExtension = authResponse.getExtension(PapeResponse.OPENID_NS_PAPE);
            if (messageExtension instanceof PapeResponse) {

                PapeResponse papeResponse = (PapeResponse) messageExtension;

                authnPolicies = papeResponse.getAuthPoliciesList();
                authenticationTime = papeResponse.getAuthDate();

            }
        }

        OpenIDAuthenticationResponse openIDAuthenticationResponse = new OpenIDAuthenticationResponse(
                authenticationTime, userId, authnPolicies, attributeMap);
        request.getSession().setAttribute(this.responseSessionAttribute, openIDAuthenticationResponse);

        response.sendRedirect(request.getContextPath() + this.redirectPage);
    } else {
        showErrorPage("No verified identifier", null, request, response);
    }
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public Configuration getConfiguration() throws IllegalArgumentException {
    if (firstTime) {
        firstTime = false;/*from  www. j  av  a2 s  . c o m*/
        HttpServletRequest req = this.getThreadLocalRequest();
        Integer identifiedPort = req.getServerPort();
        if (identifiedPort != null && identifiedPort != 0) {
            CLIENT_WEBSITE_PORT = Integer.toString(identifiedPort);
        }
        String identifiedHostname = req.getServerName();

        if (identifiedHostname == null || identifiedHostname.length() == 0
                || identifiedHostname.equals("0.0.0.0")) {
            try {
                identifiedHostname = InetAddress.getLocalHost().getCanonicalHostName();
            } catch (UnknownHostException e) {
                identifiedHostname = "127.0.0.1";
            }
        }
        CLIENT_WEBSITE_HOSTNAME = identifiedHostname;
        if (CLIENT_WEBSITE_PORT.equals("8888")) {
            CLIENT_WEBSITE_CODESVR_PORT = "9997";
        } else if (CLIENT_WEBSITE_PORT.equals("8777")) {
            CLIENT_WEBSITE_CODESVR_PORT = "9777";
        } else {
            CLIENT_WEBSITE_CODESVR_PORT = "9777";
        }
    }
    Configuration config = new Configuration();
    config.put(Configuration.CLIENT_WEBSITE_HOSTNAME_KEY, CLIENT_WEBSITE_HOSTNAME);
    config.put(Configuration.CLIENT_WEBSITE_PORT_KEY, CLIENT_WEBSITE_PORT);
    config.put(Configuration.CLIENT_WEBSITE_CODESVR_PORT_KEY, CLIENT_WEBSITE_CODESVR_PORT);
    config.put(Configuration.CLIENT_ID_KEY, CLIENT_ID);
    config.put(Configuration.CLIENT_SECRET_KEY, CLIENT_SECRET);

    return config;
}

From source file:cz.mzk.editor.server.ScanImgServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.addDateHeader("Last-Modified", new Date().getTime());
    resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
    resp.addDateHeader("Expires", DateUtils.addMonths(new Date(), 1).getTime());
    boolean full = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_FULL));
    String topSpace = req.getParameter(Constants.URL_PARAM_TOP_SPACE);
    String urlHeight = req.getParameter(Constants.URL_PARAM_HEIGHT);

    String uuid = req.getParameter(Constants.URL_PARAM_UUID);

    if (uuid == null || "".equals(uuid)) {
        uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_SCANS_PREFIX)
                + Constants.SERVLET_SCANS_PREFIX.length() + 1);
    }//  ww  w.ja va  2  s .c o m

    StringBuffer baseUrl = new StringBuffer();
    baseUrl.append("http://");
    if (!URLS.LOCALHOST()) {
        baseUrl.append(req.getServerName());
    } else {
        String hostname = config.getHostname();
        if (hostname.contains("://")) {
            baseUrl.append(hostname.substring(hostname.indexOf("://") + "://".length()));
        } else {
            baseUrl.append(hostname);
        }
    }
    StringBuffer sb = new StringBuffer();
    if (topSpace != null) {
        String metadata = IOUtils.toString(new URL(baseUrl + DJATOKA_URL_GET_METADATA + uuid),
                StandardCharsets.UTF_8);

        String height = null;
        height = metadata.substring(metadata.indexOf("ght\": \"") + 7, metadata.indexOf("\",\n\"dw"));
        String width = metadata.substring(metadata.indexOf("dth\": \"") + 7, metadata.indexOf("\",\n\"he"));

        int intHeight = Integer.parseInt(height);
        int intUrlHeight = Integer.parseInt(urlHeight);
        int intTopSpace = Integer.parseInt(topSpace);
        boolean isLower = intTopSpace > 0 && ((intHeight - intUrlHeight) < intTopSpace);
        String region = (isLower ? intHeight - intUrlHeight : (intTopSpace < 0 ? 0 : topSpace)) + ",1,"
                + urlHeight + "," + width;

        sb.append(baseUrl.toString()).append(DJATOKA_URL_FULL_PAGE_DETAIL).append(uuid)
                .append(DJATOKA_URL_REGION).append(region);

    } else {
        sb.append(baseUrl.toString())
                .append(full ? DJATOKA_URL_FULL_IMG : DJATOKA_URL + urlHeight + DJATOKA_URL_SUFFIX)
                .append(uuid);
    }
    resp.setContentType("image/jpeg");
    resp.sendRedirect(resp.encodeRedirectURL(sb.toString()));
}