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:com.tc.utils.XSPUtils.java

public static String getURL() {

    HttpServletRequest req = XSPUtils.getRequest();
    String scheme = req.getScheme(); // http
    String serverName = req.getServerName(); // hostname.com
    int serverPort = req.getServerPort(); // 80
    String contextPath = req.getContextPath(); // /mywebapp
    String servletPath = req.getServletPath(); // /servlet/MyServlet
    String pathInfo = req.getPathInfo(); // /a/b;c=123
    String queryString = req.getQueryString(); // d=789

    // Reconstruct original requesting URL
    StringBuffer url = new StringBuffer();
    url.append(scheme).append("://").append(serverName);

    if ((serverPort != 80) && (serverPort != 443)) {
        url.append(":").append(serverPort);
    }/*from  ww w.j  a  va  2  s  . com*/

    url.append(contextPath).append(servletPath);

    if (pathInfo != null) {
        url.append(pathInfo);
    }
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}

From source file:org.apache.wookie.controller.WidgetInstancesController.java

public static String checkProxy(HttpServletRequest request) {
    // set the proxy url.
    if (urlWidgetProxyServer == null) {
        Configuration properties = (Configuration) request.getSession().getServletContext()
                .getAttribute("properties"); //$NON-NLS-1$
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        if (!properties.getString("widget.proxy.scheme").trim().equals("")) //$NON-NLS-1$//$NON-NLS-2$
            scheme = properties.getString("widget.proxy.scheme"); //$NON-NLS-1$
        if (!properties.getString("widget.proxy.hostname").trim().equals("")) //$NON-NLS-1$//$NON-NLS-2$
            serverName = properties.getString("widget.proxy.hostname"); //$NON-NLS-1$
        if (!properties.getString("widget.proxy.port").trim().equals("")) //$NON-NLS-1$//$NON-NLS-2$
            serverPort = Integer.parseInt(properties.getString("widget.proxy.port")); //$NON-NLS-1$
        try {//from  w w w .  j a v a2s .co  m
            urlWidgetProxyServer = new URL(scheme, serverName, serverPort,
                    properties.getString("widget.proxy.path"));
        } catch (MalformedURLException e) {
            // ignore errors
        }
    }
    return urlWidgetProxyServer.toExternalForm();
}

From source file:nl.b3p.kaartenbalie.service.servlet.GeneralServlet.java

public static StringBuffer createBaseUrl(HttpServletRequest request, boolean useInternal) {
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath;//from  w w w  .j  av a 2s.  c o  m
    if (useInternal) {
        contextPath = KBConfiguration.KB_SERVICES_INTERNAL_CONTEXT_PATH;
    } else {
        contextPath = KBConfiguration.KB_SERVICES_CONTEXT_PATH;
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = request.getContextPath();
    }

    StringBuffer theUrl = new StringBuffer();
    String serverURI;
    if (useInternal) {
        serverURI = KBConfiguration.KB_SERVICES_INTERNAL_SERVER_URI;
    } else {
        serverURI = KBConfiguration.KB_SERVICES_SERVER_URI;
    }

    if (serverURI != null && serverURI.length() > 5) {
        theUrl.append(serverURI);
    } else {
        theUrl.append(scheme);
        theUrl.append("://");
        theUrl.append(serverName);
        if ((scheme.equals("http") && serverPort != 80) || (scheme.equals("https") && serverPort != 443)) {
            theUrl.append(":");
            theUrl.append(serverPort);
        }
    }
    theUrl.append(contextPath);

    return theUrl;
}

From source file:org.jahia.utils.Url.java

public static String appendServerNameIfNeeded(JCRNodeWrapper node, String nodeURL, HttpServletRequest request)
        throws RepositoryException, MalformedURLException {
    if (!SettingsBean.getInstance().isUrlRewriteUseAbsoluteUrls()) {
        return nodeURL;
    }//from w w w  .j av a  2s.c o m

    String requestServerName = request.getServerName();
    if (isLocalhost(requestServerName)) {
        return nodeURL;
    }

    String serverName = node.getResolveSite().getServerName();
    if (!StringUtils.isEmpty(serverName) && !isLocalhost(serverName) && !requestServerName.equals(serverName)) {
        int serverPort = SettingsBean.getInstance().getSiteURLPortOverride();

        if (serverPort == 0) {
            serverPort = request.getServerPort();
        }
        if (serverPort == 80 && "http".equals(request.getScheme())
                || serverPort == 443 && "https".equals(request.getScheme())) {
            serverPort = -1;
        }
        nodeURL = new URL(request.getScheme(), serverName, serverPort, nodeURL).toString();
    }
    return nodeURL;
}

From source file:com.feilong.servlet.http.RequestUtil.java

/**
 * scheme+serverName+port+getContextPath.
 * //from  w w w . j  a  v a  2  s.c om
 * <p>
 *  http https.
 * <p>
 * 
 * @param request
 *            the request
 * @return :http://localhost:8080/feilong/
 * @see "org.apache.catalina.connector.Request#getRequestURL()"
 * @see "org.apache.catalina.realm.RealmBase#hasUserDataPermission(Request, Response, SecurityConstraint[])"
 * @see javax.servlet.http.HttpUtils#getRequestURL(HttpServletRequest)
 */
public static String getServerRootWithContextPath(HttpServletRequest request) {
    String scheme = request.getScheme();
    int port = request.getServerPort() < 0 ? 80 : request.getServerPort();// Work around java.net.URL bug
    //*************************************************************************************
    StringBuilder sb = new StringBuilder();
    sb.append(scheme);
    sb.append("://");
    sb.append(request.getServerName());

    if ((scheme.equals(SCHEME_HTTP) && (port != 80)) || (scheme.equals(SCHEME_HTTPS) && (port != 443))) {
        sb.append(':');
        sb.append(port);
    }

    sb.append(request.getContextPath());
    return sb.toString();
}

From source file:com.googlecode.fascinator.portal.services.impl.CachingDynamicPageServiceImpl.java

public static String getURL(HttpServletRequest req, JsonSimpleConfig config) {

    // Sometimes when proxying https behind apache or another web server, if
    // this is managed by the web server the scheme may be reported
    // incorrectly to Fascinator
    String scheme = config.getString(req.getScheme(), "urlSchemeName");
    String serverName = req.getServerName(); // hostname.com
    int serverPort = req.getServerPort(); // 80
    String contextPath = req.getContextPath(); // /redbox

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://").append(serverName);

    if ((serverPort != 80) && (serverPort != 443)) {
        url.append(":").append(serverPort);
    }/*  www .j  a va 2s .  c  om*/

    url.append(contextPath).append("/");

    return url.toString();
}

From source file:net.siegmar.japtproxy.JaptProxy.java

/**
 * Analyzes (validates) request url and extract required information.
 *
 * @param request the object to populate with extracted information.
 * @throws net.siegmar.japtproxy.exception.InvalidRequestException is thrown if requested url is invalid.
 *///from w  w  w  . j a v a 2  s  .co  m
private static RequestedData buildRequestedData(final HttpServletRequest request,
        final Configuration configuration) throws InvalidRequestException {
    final String resource = request.getPathInfo();
    final RequestedData requestedData = new RequestedData();
    requestedData.setRequestedResource(resource);
    requestedData.setRequestModifiedSince(request.getDateHeader(HttpHeaderConstants.IF_MODIFIED_SINCE));

    requestedData.setUserAgent(request.getHeader(HttpHeaderConstants.USER_AGENT));
    requestedData.setUrl(getURL(request, configuration));
    requestedData.setHostUrl(getURL(request, true, configuration));
    requestedData.setScheme(request.getScheme());
    requestedData.setServerName(request.getServerName());
    requestedData.setServerPort(request.getServerPort());

    final String requestedResource = requestedData.getRequestedResource();

    // Reject if no requested resource is specified
    if (requestedResource == null) {
        throw new InvalidRequestException("Rejected request because it doesn't contain a resource request");
    }

    // Reject requests that contain /../ for security reason
    if (requestedResource.contains("/../")) {
        throw new InvalidRequestException(
                "Rejected request '" + requestedResource + "' because it contains /../");
    }

    // Reject requests that doesn't contain a backend
    final int endIdx = requestedResource.indexOf('/', 1);
    if (endIdx <= 1) {
        throw new InvalidRequestException(
                "Rejected request '" + requestedResource + "' because it doesn't specify a backend");
    }

    // Reject requests that doesn't contain a target resource
    if (requestedResource.length() == endIdx + 1) {
        throw new InvalidRequestException("Rejected request '" + requestedResource
                + "' because it doesn't specify a target " + "resource");
    }

    // Extract the backend and target resource parts of the request
    final String requestedBackend = requestedResource.substring(1, endIdx);
    final String requestedTarget = requestedResource.substring(endIdx);

    // Set requestedData
    requestedData.setRequestedTarget(requestedTarget);
    requestedData.setRequestedBackend(requestedBackend);

    return requestedData;
}

From source file:com.tc.utils.XSPUtils.java

public static String buildHostAndWebPath(FacesContext context, Database db) throws NotesException {
    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    final StringBuilder url = new StringBuilder(48);
    String webPath = db.getFilePath().replace("\\", "/");

    String scheme = request.getScheme();

    url.append(scheme);//from ww w  .  j  a  v  a 2s  . c om
    url.append("://");
    url.append(request.getServerName());

    int port = request.getServerPort();
    if (port > 0 && (("http".equalsIgnoreCase(scheme) && port != 80)
            || ("https".equalsIgnoreCase(scheme) && port != 443))) {
        url.append(':');
        url.append(port);
    }

    url.append('/');
    url.append(webPath);
    return url.toString();
}

From source file:org.alfresco.web.forms.xforms.XFormsBean.java

private static void rewriteInlineURIs(final Document schemaDocument, final String cwdAvmPath) {
    final NodeList nl = XMLUtil.combine(
            schemaDocument.getElementsByTagNameNS(NamespaceConstants.XMLSCHEMA_NS, "include"),
            schemaDocument.getElementsByTagNameNS(NamespaceConstants.XMLSCHEMA_NS, "import"));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("rewriting " + nl.getLength() + " includes");

    for (int i = 0; i < nl.getLength(); i++) {
        final Element includeEl = (Element) nl.item(i);
        if (includeEl.hasAttribute("schemaLocation")) {
            String uri = includeEl.getAttribute("schemaLocation");
            String finalURI = null;

            if (uri == null || uri.startsWith("http://") || uri.startsWith("https://")) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("not rewriting " + uri);

                continue;
            }//www.j a v a2 s. c o m

            if (uri.startsWith("webscript://")) {
                // It's a web script include / import
                final FacesContext facesContext = FacesContext.getCurrentInstance();
                final ExternalContext externalContext = facesContext.getExternalContext();
                final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

                final String baseURI = (request.getScheme() + "://" + request.getServerName() + ':'
                        + request.getServerPort() + request.getContextPath() + "/wcservice");
                String rewrittenURI = uri;

                if (uri.contains("${storeid}")) {
                    final String storeId = AVMUtil.getStoreName(cwdAvmPath);
                    rewrittenURI = uri.replace("${storeid}", storeId);
                } else if (uri.contains("{storeid}")) {
                    final String storeId = AVMUtil.getStoreName(cwdAvmPath);
                    rewrittenURI = uri.replace("{storeid}", storeId);
                } else {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("no store id specified in webscript URI " + uri);
                }

                if (uri.contains("${ticket}")) {
                    AuthenticationService authenticationService = Repository.getServiceRegistry(facesContext)
                            .getAuthenticationService();
                    final String ticket = authenticationService.getCurrentTicket();
                    rewrittenURI = rewrittenURI.replace("${ticket}", ticket);
                } else if (uri.contains("{ticket}")) {
                    AuthenticationService authenticationService = Repository.getServiceRegistry(facesContext)
                            .getAuthenticationService();
                    final String ticket = authenticationService.getCurrentTicket();
                    rewrittenURI = rewrittenURI.replace("{ticket}", ticket);
                } else {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("no ticket specified in webscript URI " + uri);
                }

                rewrittenURI = rewrittenURI.replaceAll("%26", "&");

                finalURI = baseURI + rewrittenURI.replace("webscript://", "/");

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Final URI " + finalURI);
            } else {
                // It's a web project asset include / import
                final String baseURI = (uri.charAt(0) == '/'
                        ? AVMUtil.getPreviewURI(AVMUtil.getStoreName(cwdAvmPath))
                        : AVMUtil.getPreviewURI(cwdAvmPath));

                finalURI = baseURI + uri;
            }

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("rewriting " + uri + " as " + finalURI);

            includeEl.setAttribute("schemaLocation", finalURI);
        }
    }
}

From source file:com.tc.utils.XSPUtils.java

public static String buildXpageUrl(HttpServletRequest request, String xpage, Document doc)
        throws NotesException {
    final StringBuilder url = new StringBuilder(48);

    String webPath = doc.getParentDatabase().getFilePath().replace("\\", "/");

    String scheme = request.getScheme();

    url.append(scheme);//  w w  w  . ja  v a2 s .c o  m
    url.append("://");
    url.append(request.getServerName());

    int port = request.getServerPort();
    if (port > 0 && (("http".equalsIgnoreCase(scheme) && port != 80)
            || ("https".equalsIgnoreCase(scheme) && port != 443))) {
        url.append(':');
        url.append(port);
    }

    url.append(webPath);
    url.append('/');
    url.append(xpage);
    url.append("?documentId=" + doc.getUniversalID());
    url.append("&action=openDocument");

    return url.toString();
}