Example usage for javax.servlet.http HttpServletRequest getLocalPort

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

Introduction

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

Prototype

public int getLocalPort();

Source Link

Document

Returns the Internet Protocol (IP) port number of the interface on which the request was received.

Usage

From source file:org.hippoecm.frontend.service.restproxy.RestProxyServicePlugin.java

static String createRestURI(String value, final HttpServletRequest request) {
    if (StringUtils.isEmpty(value)) {
        throw new IllegalStateException(
                "No REST service URI configured. Please set the plugin configuration property '"
                        + CONFIG_REST_URI + "'");
    }/* w w w  . j a v a2  s.  c  o m*/
    try {
        URI u = new URI(value);
        final int portNumber;
        if (u.getPort() == -1) {
            portNumber = request.getLocalPort();
        } else {
            portNumber = u.getPort();
        }
        return new URI(u.getScheme(), u.getUserInfo(), u.getHost(), portNumber, u.getRawPath(), u.getRawQuery(),
                u.getRawFragment()).toString();

    } catch (URISyntaxException e) {
        throw new IllegalStateException(
                "Invalid REST service URI configured. Please correct the plugin configuration property '"
                        + CONFIG_REST_URI + "'",
                e);
    }
}

From source file:org.ambraproject.wombat.controller.FeedbackController.java

private static Map<String, String> getUserSessionAttributes(HttpServletRequest request) {
    Map<String, String> headers = new LinkedHashMap<>();

    for (String headerName : Collections.list(request.getHeaderNames())) {
        List<String> headerValues = Collections.list(request.getHeaders(headerName));
        headers.put(headerName, headerValues.stream().collect(joinWithComma()));
    }/*from w w w . j ava 2  s  . c o m*/

    headers.put("server-name", request.getServerName() + ":" + request.getServerPort());
    headers.put("remote-addr", request.getRemoteAddr());
    headers.put("local-addr", request.getLocalAddr() + ":" + request.getLocalPort());

    /*
     * Keeping this in case more values get passed from the client other than just the visible form
     * fields
     */
    for (String paramName : Collections.list(request.getParameterNames())) {
        String[] paramValues = request.getParameterValues(paramName);
        headers.put(paramName, Stream.of(paramValues).collect(joinWithComma()));
    }

    return headers;
}

From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java

/**
 * Reconstructs the request URL string for the specified servlet
 * request. The host part is always the local IP address. The query
 * string and fragment is always omitted.
 *
 * @param request The servlet request. Must not be {@code null}.
 *
 * @return The reconstructed request URL string.
 *//*from  w w  w .j a  va2 s  .c o m*/
private static String reconstructRequestURLString(final HttpServletRequest request) {

    StringBuilder sb = new StringBuilder("http");

    if (request.isSecure())
        sb.append('s');

    sb.append("://");

    String localAddress = request.getLocalAddr();

    if (localAddress.contains(".")) {
        // IPv3 address
        sb.append(localAddress);
    } else if (localAddress.contains(":")) {
        // IPv6 address, see RFC 2732
        sb.append('[');
        sb.append(localAddress);
        sb.append(']');
    } else {
        // Don't know what to do
    }

    if (!request.isSecure() && request.getLocalPort() != 80) {
        // HTTP plain at port other than 80
        sb.append(':');
        sb.append(request.getLocalPort());
    }

    if (request.isSecure() && request.getLocalPort() != 443) {
        // HTTPS at port other than 443 (default TLS)
        sb.append(':');
        sb.append(request.getLocalPort());
    }

    String path = request.getRequestURI();

    if (path != null)
        sb.append(path);

    return sb.toString();
}

From source file:org.apache.openaz.xacml.rest.XACMLRest.java

/**
 * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
 *
 * @param request - Servlet request (from a POST/GET/PUT/etc.)
 *///  w ww  . j  av a2 s. c  o m
public static void dumpRequest(HttpServletRequest request) {
    if (logger.isDebugEnabled()) {
        // special-case for receiving heartbeat - don't need to repeatedly output all of the information
        // in multiple lines
        if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
            logger.debug("GET type=hb : heartbeat received");
            return;
        }
        logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " "
                + request.getRemotePort());
        logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
        Enumeration<String> en = request.getHeaderNames();
        logger.debug("Headers:");
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            Enumeration<String> values = request.getHeaders(element);
            while (values.hasMoreElements()) {
                String value = values.nextElement();
                logger.debug(element + ":" + value);
            }
        }
        logger.debug("Attributes:");
        en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String element = en.nextElement();
            logger.debug(element + ":" + request.getAttribute(element));
        }
        logger.debug("ContextPath: " + request.getContextPath());
        if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
            // POST and PUT are allowed to have parameters in the content, but in our usage the parameters
            // are always in the Query string.
            // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it
            // might contain a Policy file).
            // Unfortunately the request.getParameterMap method reads the content to see if there are any
            // parameters,
            // and once the content is read it cannot be read again.
            // Thus for PUT and POST we must avoid reading the content here so that the main code can read
            // it.
            logger.debug("Query String:" + request.getQueryString());
            try {
                if (request.getInputStream() == null) {
                    logger.debug("Content: No content inputStream");
                } else {
                    logger.debug("Content available: " + request.getInputStream().available());
                }
            } catch (Exception e) {
                logger.debug("Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
            }
        } else {
            logger.debug("Parameters:");
            Map<String, String[]> params = request.getParameterMap();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                String[] values = params.get(key);
                logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
            }
        }
        logger.debug("Request URL:" + request.getRequestURL());
    }
}

From source file:org.easyrec.util.core.Web.java

/**
 * This method trims a http-request with the given parameter. e.g. request:
 * /myServlet?id=1&desc=hallo --> trimRequest(request, "id") -->
 * /myServlet?desc=hallo//from   w  w w  .  ja v a2s  .  c o m
 *
 * @param request   HttpServletRequest
 * @param parameter String
 * @return String
 */
@SuppressWarnings({ "unchecked", "UnusedDeclaration" })
public static String trimRequest(HttpServletRequest request, String parameter) {

    String query = "";
    if (!Strings.isNullOrEmpty(parameter) && request.getParameterMap() != null) {
        for (final Object o : request.getParameterMap().entrySet()) {
            Entry<String, String[]> m = (Entry<String, String[]>) o;
            if (!parameter.equals(m.getKey())) {
                query += m.getKey() + "=" + m.getValue()[0] + "&";
            }
        }

        return request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort()
                + request.getContextPath() + request.getServletPath() + "?" + Text.removeLast(query);
    } else
        return null;
}

From source file:com.atlassian.jira.web.action.setup.SetupSharedVariables.java

public String getBaseUrl() {
    final HttpServletRequest request = servletVariables.getHttpRequest();

    return request.getScheme() + "://localhost:" + request.getLocalPort() + request.getContextPath();
}

From source file:org.reallysqs.server.views.CreateQueueResponseView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Queue queue = (Queue) model.get("queue");
    String location = "http://" + request.getLocalName() + ":" + request.getLocalPort()
            + request.getContextPath() + request.getServletPath() + "/queues/" + queue.getName();

    response.addHeader("Location", location);
}

From source file:org.archive.wayback.webapp.RequestMapper.java

/**
 * @param request/*from w w w. j a v a 2  s  . c o m*/
 * @return WaybackContext that handles the specific incoming HTTP request
 */
public RequestContext mapContext(HttpServletRequest request) {

    RequestContext context = null;
    String portStr = String.valueOf(request.getLocalPort());
    if (factory.containsBean(portStr)) {
        Object o = factory.getBean(portStr);
        if (o instanceof RequestContext) {
            context = (RequestContext) o;
        }
    } else {
        String contextID = getContextID(request);
        if (factory.containsBean(contextID)) {
            Object o = factory.getBean(contextID);
            if (o instanceof RequestContext) {
                context = (RequestContext) o;
            }
        }
    }
    if (context == null) {
        ArrayList<String> names = getAccessPointNamesOnPort(portStr);
        request.setAttribute("AccessPointNames", names);
    }
    return context;
}

From source file:org.jlibrary.web.servlet.JLibraryServlet.java

/**
 * Returns the root URL of this application. 
 * /*www.  j a  v a2 s. co m*/
 * @param request Requets
 * 
 * @return String root url
 */
protected String getRootURL(HttpServletRequest request) {

    String rootURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort()
            + request.getContextPath();
    return rootURL;
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.RequestLoggerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    try {/*  w  w  w.  j av  a2  s  . com*/
        if (request instanceof HttpServletRequest) {
            HttpServletRequest theRequest = (HttpServletRequest) request;
            StringBuffer requestedLocation = new StringBuffer();
            requestedLocation.append(theRequest.getLocalName()).append(":");
            requestedLocation.append(theRequest.getLocalPort());
            requestedLocation.append(theRequest.getRequestURI());
            if (theRequest.getQueryString() != null) {
                requestedLocation.append("?").append(theRequest.getQueryString());
            }
            log.debug("Incoming request: " + requestedLocation.toString());
        }
    } catch (Exception e) {
        // This shouldn't really happen, but if it does, we'll be ready for it.
    } finally {
        filterChain.doFilter(request, response);
    }
}