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:eu.comvantage.dataintegration.SparulSimulationServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */// www.ja  va 2 s. c om
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    String eventID = "";
    if (request.getParameterMap().containsKey("eventID"))
        eventID = request.getParameter("eventID");

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String uri = request.getRequestURI();
    ServletContext context = getServletContext();

    String serverName = "";
    if (request.getLocalName().startsWith("0")) {
        serverName = "localhost";
    } else {
        serverName = request.getLocalName();
    }

    simulateEvent(eventID, new String("http://" + serverName + ":" + request.getLocalPort()
            + request.getContextPath() + "/QueryDistributionServiceImpl/SPARUL"));
    out.write("'" + eventID + "' simulated. ");
}

From source file:org.mule.transport.servlet.ServletMuleMessageFactory.java

protected void copyHeaders(HttpServletRequest request, Map<String, Object> messageProperties) {
    for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        String realKey = key;//from w  ww .  j  a  va2 s  .c  o m

        if (key.startsWith(HttpConstants.X_PROPERTY_PREFIX)) {
            realKey = key.substring(2);
        }

        // Workaround for containers that strip the port from the Host header.
        // This is needed so Mule components can figure out what port they're on.
        if (HttpConstants.HEADER_HOST.equalsIgnoreCase(key)) {
            realKey = HttpConstants.HEADER_HOST;

            String value = request.getHeader(key);
            int port = request.getLocalPort();
            if (!value.contains(":") && port != 80 && port != 443) {
                value = value + ":" + port;
            }
            messageProperties.put(realKey, value);
        } else {
            Enumeration<?> valueEnum = request.getHeaders(key);
            List<?> values = EnumerationUtils.toList(valueEnum);
            if (values.size() > 1) {
                messageProperties.put(realKey, values.toArray());
            } else {
                messageProperties.put(realKey, values.get(0));
            }
        }
    }
}

From source file:org.icefaces.samples.showcase.util.SourceCodeLoaderConnection.java

@PostConstruct
private void initialize() {
    // If no logger exists for this class, create and add a new one
    if ((logger = LogManager.getLogManager().getLogger(this.getClass().getName())) == null) {
        logger = Logger.getLogger(this.getClass().getName());
        LogManager.getLogManager().addLogger(logger);
    }//from   w w  w .j  a v  a  2s.com

    // Pull the maximum cache size from web.xml using FacesUtils
    // We'll default this value if it isn't found
    MAX_CACHE_SIZE = Integer.parseInt(
            FacesUtils.getFacesParameter("org.icefaces.samples.showcase.MAX_SOURCE_CACHE_SIZE", "20971520"));

    // Next we'll try to build a URL to load the source from
    // This is basically http://localhost:8080/showcase/, but the port and address could change
    // We'll try to dynamically get this from the ExternalContext request, otherwise we'll check it from the web.xml
    //  and finally just default it
    Object request = FacesContext.getCurrentInstance().getExternalContext().getRequest();
    if ((request != null) && (request instanceof HttpServletRequest)) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String hostName = "localhost";
        try {
            //construct a url (SOURCE_SERVLET_URL) from getLocalName is not reliable
            //should use host from requestURL.
            URL requestUrl = new URL(httpRequest.getRequestURL().toString());
            hostName = requestUrl.getHost();
        } catch (MalformedURLException mfException) {
        }
        IS_SECURE = httpRequest.isSecure();
        String protocol = IS_SECURE ? "https://" : "http://";
        SOURCE_SERVLET_URL = protocol + hostName + ":" + httpRequest.getLocalPort()
                + httpRequest.getContextPath() + "/";
    } else {
        String fromFile = FacesUtils.getFacesParameter("org.icefaces.samples.showcase.SOURCE_SERVLET_URL");
        if (fromFile != null) {
            SOURCE_SERVLET_URL = fromFile;
        } else {
            SOURCE_SERVLET_URL = "http://localhost:8080/comp-suite/";
        }
    }
    SOURCE_SERVLET_URL += "sourcecodeStream.html?path=";

    //logger.info("Reading source code from url [" + SOURCE_SERVLET_URL + "].");
}

From source file:org.ambraproject.action.FeedbackAction.java

@SuppressWarnings("unchecked")
public Map<String, String> getUserSessionAttributes() {
    final Map<String, String> headers = new LinkedHashMap<String, String>();
    final HttpServletRequest request = ServletActionContext.getRequest();

    {//from   w  w w .java 2  s. c om
        final Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String headerName = (String) headerNames.nextElement();
            final List<String> headerValues = EnumerationUtils.toList(request.getHeaders(headerName));
            headers.put(headerName, StringUtils.join(headerValues.iterator(), ","));
        }
    }

    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
     */
    {
        final Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            final String paramName = (String) parameterNames.nextElement();
            final String[] paramValues = request.getParameterValues(paramName);
            headers.put(paramName, StringUtils.join(paramValues, ","));
        }
    }

    return headers;
}

From source file:uk.ac.ebi.arrayexpress.servlets.HttpProxyServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response, RequestType requestType)
        throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url = url.replaceFirst("http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
        if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
            url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
        }/*  w  w  w  .ja va  2 s.  c o m*/
        logger.debug("Will access [{}]", url);

        GetMethod getMethod = new GetMethod(url);

        if (null != queryString) {
            queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
            getMethod.setQueryString(queryString);
        }

        Enumeration requestHeaders = request.getHeaderNames();
        while (requestHeaders.hasMoreElements()) {
            String name = (String) requestHeaders.nextElement();
            String value = request.getHeader(name);
            if (null != value) {
                getMethod.setRequestHeader(name, value);
            }
        }

        try {
            httpClient.executeMethod(getMethod);

            int statusCode = getMethod.getStatusCode();
            long contentLength = getMethod.getResponseContentLength();
            logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

            Header[] responseHeaders = getMethod.getResponseHeaders();
            for (Header responseHeader : responseHeaders) {
                String name = responseHeader.getName();
                String value = responseHeader.getValue();
                if (null != name && null != value && !(name.equals("Server") || name.equals("Date")
                        || name.equals("Transfer-Encoding"))) {
                    response.setHeader(responseHeader.getName(), responseHeader.getValue());
                }
            }

            if (200 != statusCode) {
                response.setStatus(statusCode);
            }

            InputStream inStream = getMethod.getResponseBodyAsStream();
            if (null != inStream) {
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

                CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
                while (in.read(buffer) >= 0) {
                    buffer.flip();
                    out.append(buffer);
                    buffer.clear();
                }

                in.close();
                out.close();
            }
        } catch (Exception x) {
            if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                logger.warn("Client aborted connection");
            } else {
                logger.error("Caught an exception:", x);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
            }
        } finally {
            getMethod.releaseConnection();
        }
    }
}

From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java

/**
 * Creates a thumbnail for the layer as a Resource, and updates the layer with the new thumbnail
 * @param ws The workspace of the layer/*from ww w . j  av a  2 s  .co m*/
 * @param layer The layer or layerGroup to get the thumbnail for
 * @return The thumbnail image as a Resource
 * @throws Exception
 */
protected void createThumbnail(WorkspaceInfo ws, PublishedInfo layer, HttpServletRequest baseRequest)
        throws Exception {
    //Sync against this map/layer
    Semaphore s = semaphores.get(layer);
    s.acquire();
    try {
        //(SUITE-1072) Initialize the thumbnail to a blank image in case the WMS request crashes geoserver
        BufferedImage blankImage = new BufferedImage(THUMBNAIL_SIZE * 2, THUMBNAIL_SIZE * 2,
                BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g = blankImage.createGraphics();
        g.setColor(new Color(0, 0, 0, 0));
        g.fillRect(0, 0, blankImage.getWidth(), blankImage.getHeight());
        writeThumbnail(layer, blankImage);

        //Set up getMap request
        String url = baseRequest.getScheme() + "://localhost:" + baseRequest.getLocalPort()
                + baseRequest.getContextPath() + "/" + ws.getName() + "/wms/reflect";

        url += "?FORMAT=" + MIME_TYPE;

        ReferencedEnvelope bbox = null;
        if (layer instanceof LayerInfo) {
            url += "&LAYERS=" + layer.getName();
            url += "&STYLES=" + ((LayerInfo) layer).getDefaultStyle().getName();
            bbox = ((LayerInfo) layer).getResource().boundingBox();
        } else if (layer instanceof LayerGroupInfo) {

            LayerGroupHelper helper = new LayerGroupHelper((LayerGroupInfo) layer);
            bbox = ((LayerGroupInfo) layer).getBounds();
            url += "&CRS=" + CRS.toSRS(bbox.getCoordinateReferenceSystem());

            List<LayerInfo> layerList = helper.allLayersForRendering();
            if (layerList.size() > 0) {
                url += "&LAYERS=";
                for (int i = 0; i < layerList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    url += layerList.get(i) == null ? "" : layerList.get(i).getName();
                }
            }
            List<StyleInfo> styleList = helper.allStylesForRendering();
            if (styleList.size() > 0) {
                url += "&STYLES=";
                for (int i = 0; i < styleList.size(); i++) {
                    if (i > 0) {
                        url += ",";
                    }
                    if (styleList.get(i) == null) {
                        url += layerList.get(i).getDefaultStyle() == null ? ""
                                : layerList.get(i).getDefaultStyle().getName();
                    } else {
                        url += styleList.get(i) == null ? "" : styleList.get(i).getName();
                    }
                }
            }
        } else {
            throw new RuntimeException("layer must be one of LayerInfo or LayerGroupInfo");
        }
        //Set the size of the HR thumbnail
        //Take the smallest bbox dimension as the min dimension. We can then crop the other 
        //dimension to give a square thumbnail
        url += "&BBOX=" + ((float) bbox.getMinX()) + "," + ((float) bbox.getMinY()) + ","
                + ((float) bbox.getMaxX()) + "," + ((float) bbox.getMaxY());
        if (bbox.getWidth() < bbox.getHeight()) {
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE);
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getHeight() / bbox.getWidth()));
        } else {
            url += "&HEIGHT=" + (2 * THUMBNAIL_SIZE);
            url += "&WIDTH=" + (2 * THUMBNAIL_SIZE * Math.round(bbox.getWidth() / bbox.getHeight()));
        }

        //Run the getMap request through the WMS Reflector
        //WebMap response = wms.reflect(request);            
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedImage image = ImageIO.read(con.getInputStream());
        if (image == null) {
            throw new RuntimeException(
                    "Failed to encode thumbnail for " + ws.getName() + ":" + layer.getName());
        }
        writeThumbnail(layer, image);
    } finally {
        s.release();
    }
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:org.infoglue.cms.util.CmsPropertyHandler.java

public static void registerDefaultSchemeAndPort(HttpServletRequest request) {
    if (defaultScheme == null || defaultPort == null && request != null) {
        defaultScheme = request.getScheme();
        defaultPort = request.getLocalPort();
        logger.info("Registered defaultScheme:" + defaultScheme + " and defaultPort:" + defaultPort);
    }/*  w w w.  j  a  v  a2s . com*/
}

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   ww w  .j  av a  2 s .c o m
        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:gr.forth.ics.isl.Index.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w. j a  v a  2s .  co  m
 *
 * @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");
    PrintWriter out = response.getWriter();

    String id = request.getParameter("id");
    String sourceFile = request.getParameter("sourceFile");
    //        String sourceFilename = request.getParameter("sourceFilename");
    String generator = request.getParameter("generator");
    String uuidSize = request.getParameter("uuidSize");
    String outputFormat = request.getParameter("output");

    int uuidSizeInt = 2;

    if (uuidSize != null) {
        try {
            uuidSizeInt = Integer.parseInt(uuidSize);
        } catch (NumberFormatException ex) {

        }
    }

    Mapper map = new Mapper();

    try {
        String serverIP = request.getLocalAddr();

        if (serverIP.equals("0:0:0:0:0:0:0:1")) {//Localhost
            serverIP = "localhost";
        }
        System.out.println("http://" + serverIP + ":" + request.getLocalPort() + "/3MEditor/Services?id=" + id
                + "&output=text/xml&method=export");
        X3MLEngine engine = map.engine("http://" + serverIP + ":" + request.getLocalPort()
                + "/3MEditor/Services?id=" + id + "&output=text/xml&method=export");
        X3MLEngine.Output output = engine.execute(map.documentFromString(sourceFile),
                map.policy(generator, uuidSizeInt));
        if (X3MLEngine.exceptionMessagesList.length() > 0) {
            out.println(X3MLEngine.exceptionMessagesList
                    .replaceAll("(?<!\\A)eu\\.delving\\.x3ml\\.X3MLEngine\\$X3MLException:", "\n$0"));
        }
        if (outputFormat == null || outputFormat.equals("RDF/XML")) {
            OutputStream os = new WriterOutputStream(out);
            PrintStream ps = new PrintStream(os);
            output.writeXML(ps);
        } else if (outputFormat.equals("N-triples")) {
            out.println(output.toString());
        } else if (outputFormat.equals("Turtle")) {
            OutputStream os = new WriterOutputStream(out);
            PrintStream ps = new PrintStream(os);
            output.write(ps, "text/turtle");

        }

    } catch (X3MLEngine.X3MLException ex) {
        ex.printStackTrace(out);
    } catch (Exception ex) {
        ex.printStackTrace(out);
    }

    out.close();

}