Example usage for javax.servlet ServletRequest getServerName

List of usage examples for javax.servlet ServletRequest getServerName

Introduction

In this page you can find the example usage for javax.servlet ServletRequest 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:org.jboss.dashboard.ui.components.URLMarkupGenerator.java

/**
 * Get the base href for current request
 * @param request/*from   w ww.j a va 2s .c om*/
 * @return a String with the form http://host[:port]/[context/]
 * @throws IOException
 */
public String getBaseHref(ServletRequest request) throws IOException {
    StringBuffer sb = new StringBuffer();
    String context = ((HttpServletRequest) request).getContextPath();
    String protocol = request.getScheme();
    while (context.startsWith("/")) {
        context = context.substring(1);
    }
    sb.append(protocol.toLowerCase()).append("://").append(request.getServerName());
    if (request.getServerPort() != 80) {
        sb.append(":").append(request.getServerPort());
    }
    sb.append("/");
    if (!StringUtils.isEmpty(context)) {
        sb.append(context).append("/");
    }
    return sb.toString();
}

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 {/*from www.ja  va2 s  .  co m*/
        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:org.ovirt.vdsmfake.servlet.XmlRpcFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//from   ww w  . ja  va  2s  . com
        final String method = ((HttpServletRequest) request).getMethod();

        if ("GET".equals(method)) {
            response.setContentType("text/plain");
            response.getWriter().write("Hello, this is VDSM Fake.");
            return;
        }

        if (!"POST".equals(method)) {
            response.setContentType("text/plain");
            response.getWriter().write("Unsupported method: " + method);
            return;
        }

        ContextHolder.init();
        ContextHolder.setServerName(request.getServerName());

        final AppConfig conf = AppConfig.getInstance();

        final CustomHttpServletRequestWrapper wrapper = new CustomHttpServletRequestWrapper(
                (HttpServletRequest) request);

        final CustomHttpServletResponseWrapper responseWrapper = new CustomHttpServletResponseWrapper(
                (HttpServletResponse) response);

        // fix method call name - add namespace of method (required by Apache XMLRPC)
        final Document doc = XMLUtils.parseDocument(wrapper.getInputStream());
        final XPath xp = XPath.newInstance("/methodCall/methodName");
        final Element el = (Element) xp.selectSingleNode(doc);
        final String methodName = el.getText();

        final long tm = System.currentTimeMillis();

        // append namespace
        if (!conf.isProxyActive()) {
            el.setText(METHOD_CALL_NS + "." + el.getText());
        }

        // write back the new XML data
        wrapper.setInputStreamData(XMLUtils.serializeDocument(doc));

        log.info("[{}] {} starting...", new Object[] { request.getServerName(), methodName });

        chain.doFilter(wrapper, responseWrapper);

        // write communication into files
        if (conf.isLogDirSet() && conf.isMethodLoggingEnabled(methodName)) {
            int fIndex = logCounter.incrementAndGet();

            FileUtils.writeByteArrayToFile(new File(conf.getLogDir(), getPrefix(fIndex) + "_req_" + methodName),
                    wrapper.getInputStreamData());
            FileUtils.writeByteArrayToFile(new File(conf.getLogDir(), getPrefix(fIndex) + "_res_" + methodName),
                    responseWrapper.getOutputStreamData());
        }

        // write response
        responseWrapper.writeDataToStream();

        // log request info
        log.info("[{}] {} done. ({} ms, {} bytes)", new Object[] { request.getServerName(), methodName,
                Long.valueOf(System.currentTimeMillis() - tm), responseWrapper.getOutputStreamData().length });
    } catch (Exception e) {
        log.error("Cannot filter request", e);
        throw new ServletException("Error during request processing", e);
    } finally {
        ContextHolder.clear();
    }
}

From source file:org.deegree.services.csw.CSWController.java

private void sendSoapException(SOAPEnvelope soapDoc, SOAPFactory factory, HttpResponseBuffer response,
        OWSException e, ServletRequest request, SOAPVersion version) throws OMException, ServletException {
    XMLExceptionSerializer serializer = getExceptionSerializer(parseVersion("1.2.0"));
    sendSOAPException(soapDoc.getHeader(), factory, response, e, serializer, null, null,
            request.getServerName(), request.getCharacterEncoding());
}

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

/**
 * Performs the redirect (or forward) to the login form URL.
 *//*from w ww .j  ava  2s.  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:net.sf.j2ep.RewriteFilter.java

/**
 * Rewrites the outgoing stream to make sure URLs and headers
 * are correct. The incoming request is first processed to 
 * identify what resource we want to proxy.
 * //from  ww  w.j a v a  2s  .c  om
 * @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");
    if (response.isCommitted()) {
        log.info("Not proxying, already committed.");
        return;
    } else if (!(request instanceof HttpServletRequest)) {
        log.info("Request is not HttpRequest, will only handle HttpRequests.");
        return;
    } else if (!(response instanceof HttpServletResponse)) {
        log.info("Request is not HttpResponse, will only handle HttpResponses.");
        return;
    } else {

        Server server = serverChain.evaluate(httpRequest);
        if (server == null) {
            log.info("Could not find a rule for this request, will not do anything.");
            filterChain.doFilter(request, response);
        } else {
            httpRequest.setAttribute("proxyServer", server);

            String ownHostName = request.getServerName() + ":" + request.getServerPort();
            UrlRewritingResponseWrapper wrappedResponse;
            wrappedResponse = new UrlRewritingResponseWrapper(httpResponse, server, ownHostName, httpRequest,
                    serverChain);

            filterChain.doFilter(httpRequest, wrappedResponse);

            wrappedResponse.processStream();
        }
    }
}

From source file:org.deegree.services.wfs.WebFeatureService.java

private void sendSoapException(SOAPEnvelope soapDoc, SOAPFactory factory, HttpResponseBuffer response,
        OWSException e, ServletRequest request, Version requestVersion) throws OMException, ServletException {
    XMLExceptionSerializer serializer = getExceptionSerializer(requestVersion);
    sendSOAPException(soapDoc.getHeader(), factory, response, e, serializer, null, null,
            request.getServerName(), request.getCharacterEncoding());
}

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());
    }//w w  w  .ja v  a2 s .  c  om
    return serverUrlBuffer.toString();
}

From source file:se.natusoft.osgi.aps.rpchttpextender.servlet.RPCServlet.java

/**
 * Catch our host and port information which as far as I can determine is only possible to get from a request.
 *
 * @param req/*ww  w  . j  a  va2s  .com*/
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
    if (this.rpcBaseUrl == null) {
        String protocol = req.getProtocol().split("/")[0].toLowerCase();
        if (req.getServerName() != null) {
            this.serverHost = req.getServerName();
        } else if (req.getLocalName() != null) {
            this.serverHost = req.getLocalName();
        }
        if (this.serverHost.equals("localhost")) {
            this.serverHost = InetAddress.getLocalHost().getHostName();
        }
        this.serverPort = req.getServerPort();
        this.rpcBaseUrl = protocol + "://" + this.serverHost + ":" + this.serverPort + "/apsrpc/";

        try {
            onServiceAvailable(this.discoveryServiceTracker.allocateService(), null);
            this.discoveryServiceTracker.releaseService();
        } catch (Exception e) {
        }
    }
    super.service(req, resp);
}

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 + "\"");
        }/*from   ww w.  j  av  a2 s .  c om*/
    } 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?
    }
}