Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

From source file:net.sf.qooxdoo.rpc.RpcServlet.java

protected String getContextURL(HttpServletRequest request) {
    // reconstruct the start of the URL
    StringBuffer contextURL = new StringBuffer();
    String scheme = request.getScheme();
    int port = request.getServerPort();

    contextURL.append(scheme);/*w  ww .ja v  a2s.c om*/
    contextURL.append("://");
    contextURL.append(request.getServerName());
    if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
        contextURL.append(':');
        contextURL.append(request.getServerPort());
    }
    contextURL.append(request.getContextPath());

    return contextURL.toString();
}

From source file:org.apache.jetspeed.portlets.spaces.PageNavigator.java

public String getAbsoluteUrl(String relativePath, RenderResponse renderResponse, RequestContext rc) {
    // only rewrite a non-absolute url
    if (relativePath != null && relativePath.indexOf("://") == -1 && relativePath.indexOf("mailto:") == -1) {
        HttpServletRequest request = rc.getRequest();
        StringBuffer path = new StringBuffer();

        if (!rc.getPortalURL().isRelativeOnly()) {
            if (this.baseUrlAccess == null) {
                path.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
                        .append(request.getServerPort());
            } else {
                path.append(baseUrlAccess.getServerScheme()).append("://").append(baseUrlAccess.getServerName())
                        .append(":").append(baseUrlAccess.getServerPort());
            }//from  w  w w .j a  v  a 2  s  . c  o  m
        }

        return renderResponse.encodeURL(path.append(request.getContextPath()).append(request.getServletPath())
                .append(relativePath).toString());
    } else {
        return relativePath;
    }
}

From source file:org.sample.asyncserver.TestServlet.java

/**
 * Processes requests for both HTTP/*ww w  . j  a va  2  s .  c om*/
 * <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");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TestServlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/webresources/fruits");
    String result = target.request().get(String.class);
    out.println("Waited for 3 seconds ...<br>");
    out.println("Received response: " + result);
    out.println("</body>");
    out.println("</html>");
}

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

/**
 * Processes requests for both HTTP/*w  w w  .j a v  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: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 {/*  w ww.j  a va  2s. co  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:fr.paris.lutece.portal.service.util.AppPathService.java

/**
 * Return the url of the webapp, built from the request
 *
 * @param request The HttpServletRequest
 * @return strBase the webapp url/*from w w  w  .j  a v a2 s.  co  m*/
 */
public static String getBaseUrl(HttpServletRequest request) {
    if (request == null) {
        return getBaseUrl();
    }

    String strBase;

    // Search for a Virtual Host Base Url defined in the request
    strBase = getVirtualHostBaseUrl(request);

    // If not found, get the base url from session
    if ((strBase == null) || strBase.equals(StringUtils.EMPTY)) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            Object oBase = session.getAttribute(SESSION_BASE_URL);

            if (oBase != null) {
                strBase = (String) oBase;
            }
        }
    }

    // If not found, get the base url from the config.properties
    if ((strBase == null) || (strBase.equals(StringUtils.EMPTY))) {
        strBase = AppPropertiesService.getProperty(PROPERTY_BASE_URL);
    }

    if ((strBase == null) || (strBase.equals(StringUtils.EMPTY))) {
        // Dynamic base URL if not defined in the properties
        strBase = request.getScheme() + DOUBLE_POINTS + SLASH + SLASH + request.getServerName();

        int nPort = request.getServerPort();

        if (nPort != PORT_NUMBER_HTTP) {
            strBase += (DOUBLE_POINTS + nPort);
        }

        strBase += request.getContextPath();
    }

    if (!strBase.endsWith(SLASH)) {
        strBase += SLASH;
    }

    return strBase;
}

From source file:com.jaspersoft.jasperserver.war.OlapPrint.java

/**
 * Set parameters to include the chart in the printed Excel or PDF
 *
 * @param chartRef//from   w  w w .  ja  v  a 2s.  com
 * @param request
 * @return
 */
private Map getChartParameters(String chartRef, HttpServletRequest request) {
    Map parameters = new HashMap();

    // add parameters and image from chart if visible
    ChartComponent chart = (ChartComponent) request.getSession().getAttribute(chartRef);
    if (chart == null || !chart.isVisible()) {
        return parameters;
    }

    String host = request.getServerName();
    int port = request.getServerPort();
    String location = request.getContextPath();
    String scheme = request.getScheme();

    String chartServlet = scheme + "://" + host + ":" + port + location + "/GetChart";
    parameters.put("chartimage", chartServlet + "?filename=" + chart.getFilename());
    parameters.put("chartheight", new Integer(chart.getChartHeight()));
    parameters.put("chartwidth", new Integer(chart.getChartWidth()));
    return parameters;
}

From source file:com.haulmont.cuba.core.sys.remoting.RemotingServlet.java

/**
 * Check correctness of some configuration parameters and log the warning if necessary.
 *///from  w  w  w .  j  av a2  s .c o  m
protected void checkConfiguration(HttpServletRequest request) {
    if (!checkCompleted) {
        GlobalConfig config = AppBeans.get(Configuration.class).getConfig(GlobalConfig.class);
        if (config.getLogIncorrectWebAppPropertiesEnabled()) {
            StringBuilder sb = new StringBuilder();
            if (!request.getServerName().equals(config.getWebHostName())) {
                sb.append("***** cuba.webHostName=").append(config.getWebHostName()).append(", actual=")
                        .append(request.getServerName()).append("\n");
            }
            if (request.getServerPort() != Integer.parseInt(config.getWebPort())) {
                sb.append("***** cuba.webPort=").append(config.getWebPort()).append(", actual=")
                        .append(request.getServerPort()).append("\n");
            }
            String contextPath = request.getContextPath();
            if (contextPath.startsWith("/"))
                contextPath = contextPath.substring(1);
            if (!contextPath.equals(config.getWebContextName())) {
                sb.append("***** cuba.webContextName=").append(config.getWebContextName()).append(", actual=")
                        .append(contextPath).append("\n");
            }
            if (sb.length() > 0) {
                sb.insert(0, "\n*****\n");
                sb.append("*****");
                log.warn(" Invalid configuration parameters that may cause problems:" + sb.toString());
            }
        }
        checkCompleted = true;
    }
}

From source file:com.indeed.imhotep.web.BashScriptServlet.java

@RequestMapping("/iql.sh")
@ResponseBody//from   w  w  w.j a  va 2s .co m
protected String doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setHeader("content-disposition", "attachment; filename=iql.sh");
    final String server = req.getServerName();
    final String protocol;
    if (server.contains("qa.indeed") || server.contains("stage.indeed") || server.contains("indeed.com")) {
        protocol = "https://";
    } else {
        protocol = "http://";
    }

    final URL scriptResourceURL = Resources.getResource("iql.sh");
    final String script = Resources.toString(scriptResourceURL, Charsets.UTF_8);
    final String serverURLVariable = "SERVER_URL=" + protocol + server + ":" + req.getServerPort()
            + req.getContextPath() + "/query\n";
    return serverURLVariable + script;
}

From source file:org.infoglue.calendar.actions.ViewEntrySearchAction.java

/**
 * This is the entry point for the main listing.
 *//*  w w  w . jav a2  s .co m*/

public String execute() throws Exception {
    Session dbSession = getSession(true);

    initialize(dbSession);

    if (this.searchHashCode != null && !this.searchHashCode.equals("")) {
        log.debug("Getting search args from session..." + this.searchHashCode);
        HttpSession session = ServletActionContext.getRequest().getSession();

        this.searchFirstName = (String) session.getAttribute("request_" + searchHashCode + "_searchFirstName");
        this.searchLastName = (String) session.getAttribute("request_" + searchHashCode + "_searchLastName");
        this.searchEmail = (String) session.getAttribute("request_" + searchHashCode + "_searchEmail");
        this.onlyFutureEvents = Boolean
                .parseBoolean((String) session.getAttribute("request_" + searchHashCode + "_onlyFutureEvents"));
        this.searchEventId = (Long[]) session.getAttribute("request_" + searchHashCode + "_searchEventId");
        this.categoryAttributesMap = (Map) session
                .getAttribute("request_" + searchHashCode + "_categoryAttributesMap");
        this.andSearch = (String) session.getAttribute("request_" + searchHashCode + "_andSearch");
        this.locationId = (String[]) session.getAttribute("request_" + searchHashCode + "_locationId");
    } else {
        log.debug("Getting search args from request...");

        int i = 0;
        String idKey = ServletActionContext.getRequest().getParameter("categoryAttributeId_" + i);
        log.info("idKey:" + idKey);
        while (idKey != null && idKey.length() > 0) {
            String[] categoryIds = ServletActionContext.getRequest()
                    .getParameterValues("categoryAttribute_" + idKey + "_categoryId");
            log.info("categoryIds:" + categoryIds);
            if (categoryIds != null) {
                Long[] categoryIdsLong = new Long[categoryIds.length];
                for (int j = 0; j < categoryIds.length; j++)
                    categoryIdsLong[j] = new Long(categoryIds[j]);

                categoryAttributesMap.put(idKey, categoryIdsLong);
            }

            i++;
            idKey = ServletActionContext.getRequest().getParameter("categoryAttributeId_" + i);
            log.info("idKey:" + idKey);
        }
        log.info("searchEventId:::::" + this.searchEventId);
        log.info("andSearch:" + this.andSearch);

        this.andSearch = ServletActionContext.getRequest().getParameter("andSearch");
        log.info("andSearch:" + andSearch);
    }

    this.entries = EntryController.getController().getEntryList(this.getInfoGlueRemoteUser(),
            this.getInfoGlueRemoteUserRoles(), this.getInfoGlueRemoteUserGroups(), searchFirstName,
            searchLastName, searchEmail, onlyFutureEvents, searchEventId, categoryAttributesMap,
            Boolean.parseBoolean(andSearch), locationId, dbSession);

    List<Event> events = new ArrayList<Event>();
    String eventName = "";

    String emailAddresses = "";
    Long entryTypeId = null;
    Iterator entriesIterator = entries.iterator();
    while (entriesIterator.hasNext()) {
        Entry entry = (Entry) entriesIterator.next();
        if (!events.contains(entry.getEvent())) {
            String name = entry.getEvent().getLocalizedName(this.getLanguageCode(), "sv");
            if (name == null) {
                EventVersion eventVersion = this.getEventVersion(entry.getEvent());
                if (eventVersion != null)
                    name = eventVersion.getLocalizedName(this.getLanguageCode(), "sv");
            }

            eventName += (eventName.equals("") ? "" : ", ") + name;
            events.add(entry.getEvent());
        }

        if (entryTypeId == null)
            entryTypeId = entry.getEvent().getEntryFormId();

        if (emailAddresses.length() != 0)
            emailAddresses += ";" + entry.getEmail();
        else
            emailAddresses += entry.getEmail();
    }

    HttpSession session = ServletActionContext.getRequest().getSession();

    this.searchHashCode = "" + ServletActionContext.getRequest().hashCode();
    log.debug("searchHashCode:" + searchHashCode);
    session.setAttribute("request_" + searchHashCode + "_emailAddresses", emailAddresses);

    session.setAttribute("request_" + searchHashCode + "_searchFirstName", searchFirstName);
    session.setAttribute("request_" + searchHashCode + "_searchLastName", searchLastName);
    session.setAttribute("request_" + searchHashCode + "_searchEmail", searchEmail);
    session.setAttribute("request_" + searchHashCode + "_onlyFutureEvents", "" + onlyFutureEvents);
    session.setAttribute("request_" + searchHashCode + "_searchEventId", searchEventId);
    session.setAttribute("request_" + searchHashCode + "_categoryAttributesMap", categoryAttributesMap);
    session.setAttribute("request_" + searchHashCode + "_andSearch", andSearch);
    session.setAttribute("request_" + searchHashCode + "_locationId", locationId);

    // should we create result files?
    boolean exportEntryResults = PropertyHelper.getBooleanProperty("exportEntryResults");
    if (entries.size() > 0 && exportEntryResults) {
        Map parameters = new HashMap();
        parameters.put("headLine", "Entries found for: " + eventName);

        EventType eventType = EventTypeController.getController().getEventType(entryTypeId, getSession());
        List attributes = ContentTypeDefinitionController.getController()
                .getContentTypeAttributes(eventType.getSchemaValue());
        List attributeNames = new ArrayList();
        Iterator attributesIterator = attributes.iterator();
        while (attributesIterator.hasNext()) {
            ContentTypeAttribute attribute = (ContentTypeAttribute) attributesIterator.next();
            attributeNames.add(attribute.getName());
        }
        parameters.put("attributes", attributes);
        parameters.put("attributeNames", attributeNames);

        HttpServletRequest request = ServletActionContext.getRequest();
        EntrySearchResultfilesConstructor results = new EntrySearchResultfilesConstructor(parameters, entries,
                getTempFilePath(), request.getScheme(), request.getServerName(), request.getServerPort(),
                resultValues, this, entryTypeId.toString());
        searchResultFiles = results.getResults();
    }

    return Action.SUCCESS;
}