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:org.openmrs.module.owa.web.controller.OwaRestController.java

@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST)
@ResponseBody/* w  w  w .  jav  a2  s  .c  om*/
public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    List<App> appList = new ArrayList<>();
    if (Context.hasPrivilege("Manage OWA")) {
        String message;
        HttpSession session = request.getSession();
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            File uploadedFile = new File(file.getOriginalFilename());
            file.transferTo(uploadedFile);
            try (ZipFile zip = new ZipFile(uploadedFile)) {
                if (zip.size() == 0) {
                    message = messageSourceService.getMessage("owa.blank_zip");
                    log.warn("Zip file is empty");
                    session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                    response.sendError(500, message);
                } else {
                    ZipEntry entry = zip.getEntry("manifest.webapp");
                    if (entry == null) {
                        message = messageSourceService.getMessage("owa.manifest_not_found");
                        log.warn("Manifest file could not be found in app");
                        uploadedFile.delete();
                        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                        response.sendError(500, message);
                    } else {
                        String contextPath = request.getScheme() + "://" + request.getServerName() + ":"
                                + request.getServerPort() + request.getContextPath();
                        appManager.installApp(uploadedFile, fileName, contextPath);
                        message = messageSourceService.getMessage("owa.app_installed");
                        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
                    }
                }
            } catch (Exception e) {
                message = messageSourceService.getMessage("owa.not_a_zip");
                log.warn("App is not a zip archive");
                uploadedFile.delete();
                session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
                response.sendError(500, message);
            }
        }
        appManager.reloadApps();
        appList = appManager.getApps();
    }
    return appList;
}

From source file:axiom.servlet.AbstractServletClient.java

void sendRedirect(HttpServletRequest req, HttpServletResponse res, String url) {
    String location = url;//from w  ww . ja va2s  . com

    if (url.indexOf("://") == -1) {
        // need to transform a relative URL into an absolute one
        String scheme = req.getScheme();
        StringBuffer loc = new StringBuffer(scheme);

        loc.append("://");
        String hostname = req.getServerName();
        boolean forwarded = false;
        if (req.getHeader("X-Forwarded-Host") != null) {
            hostname = req.getHeader("X-Forwarded-Host");
            forwarded = true;
        }
        loc.append(hostname);

        int p = (!forwarded) ? req.getServerPort() : 80;

        // check if we need to include server port
        if ((p > 0) && (("http".equals(scheme) && (p != 80)) || ("https".equals(scheme) && (p != 443)))) {
            loc.append(":");
            loc.append(p);
        }

        if (!url.startsWith("/")) {
            String requri = req.getRequestURI();
            int lastSlash = requri.lastIndexOf("/");

            if (lastSlash == (requri.length() - 1)) {
                loc.append(requri);
            } else if (lastSlash > -1) {
                loc.append(requri.substring(0, lastSlash + 1));
            } else {
                loc.append("/");
            }
        }

        loc.append(url);
        location = loc.toString();
    }

    // send status code 303 for HTTP 1.1, 302 otherwise
    if (isOneDotOne(req.getProtocol())) {
        res.setStatus(HttpServletResponse.SC_SEE_OTHER);
    } else {
        res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }

    res.setContentType("text/html");
    res.setHeader("Location", location);
}

From source file:org.jahia.services.seo.urlrewrite.ServerNameToSiteMapper.java

public void analyzeLink(HttpServletRequest request, String ctx, String language, String siteKey, String path) {

    String currentSiteKey = getSiteKeyByServerName(request);
    boolean matches = currentSiteKey.equals(siteKey);
    request.setAttribute(ATTR_NAME_SITE_KEY_MATCHES, Boolean.valueOf(matches));

    try {//ww w.  ja  va  2  s.c  o  m
        boolean languageMatches = JahiaSitesService.getInstance().getSiteDefaultLanguage(siteKey)
                .equals(language);
        request.setAttribute(ATTR_NAME_DEFAULT_LANG_MATCHES, languageMatches);
        request.setAttribute(ATTR_NAME_LANG_TOKEN, languageMatches ? "" : "/" + language);
    } catch (JahiaException e) {
        logger.error("Error resolving language " + language + " for siteKey '" + siteKey + "'", e);
    }

    if (!matches && currentSiteKey.length() > 0 && SettingsBean.getInstance().isUrlRewriteUseAbsoluteUrls()) {
        JahiaSite siteByKey = null;
        try {
            siteByKey = JahiaSitesService.getInstance().getSiteByKey(siteKey);
        } catch (JahiaException e) {
            logger.error("Error resolving site for site key " + siteKey, e);
        }
        String serverName = siteByKey != null && !Url.isLocalhost(siteByKey.getServerName())
                ? siteByKey.getServerName()
                : null;
        if (StringUtils.isNotEmpty(serverName)) {
            int port = SettingsBean.getInstance().getSiteURLPortOverride();
            if (port == 0) {
                port = request.getServerPort();
            }
            if (!(port == 80 && "http".equals(request.getScheme())
                    || port == 443 && "https".equals(request.getScheme()))) {
                serverName = new StringBuilder().append(serverName).append(":").append(port).toString();
            }
        }
        request.setAttribute(ATTR_NAME_SITE_KEY_FOR_LINK, serverName);
        request.setAttribute(ATTR_NAME_SERVERNAME_FOR_LINK,
                serverName != null ? (request.getScheme() + "://" + serverName) : null);
    }

    checkCmsPrefix(request, ctx, path);

    if (logger.isDebugEnabled()) {
        logger.debug("analyzeLink({}, {}, {}, {}) | currentSiteKey={} targetSiteKey={} matches={}",
                new Object[] { ctx, language, siteKey, path, currentSiteKey, siteKey, matches });
    }
}

From source file:com.mirth.connect.server.servlets.WebStartServlet.java

private Document getAdministratorJnlp(HttpServletRequest request) throws Exception {
    InputStream is = ResourceUtil.getResourceStream(this.getClass(), "mirth-client.jnlp");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    IOUtils.closeQuietly(is);/*from  ww  w. j a va  2s .  c om*/

    Element jnlpElement = document.getDocumentElement();

    // Change the title to include the version of Mirth Connect
    PropertiesConfiguration versionProperties = new PropertiesConfiguration();
    versionProperties.setDelimiterParsingDisabled(true);
    versionProperties.load(ResourceUtil.getResourceStream(getClass(), "version.properties"));
    String version = versionProperties.getString("mirth.version");

    Element informationElement = (Element) jnlpElement.getElementsByTagName("information").item(0);
    Element title = (Element) informationElement.getElementsByTagName("title").item(0);
    String titleText = title.getTextContent() + " " + version;

    // If a server name is set, prepend the application title with it
    String serverName = configurationController.getServerSettings().getServerName();
    if (StringUtils.isNotBlank(serverName)) {
        titleText = serverName + " - " + titleText;
    }

    title.setTextContent(titleText);

    String scheme = request.getScheme();
    String serverHostname = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    String codebase = scheme + "://" + serverHostname + ":" + serverPort + contextPath;

    PropertiesConfiguration mirthProperties = new PropertiesConfiguration();
    mirthProperties.setDelimiterParsingDisabled(true);
    mirthProperties.load(ResourceUtil.getResourceStream(getClass(), "mirth.properties"));

    String server = null;

    if (StringUtils.isNotBlank(mirthProperties.getString("server.url"))) {
        server = mirthProperties.getString("server.url");
    } else {
        int httpsPort = mirthProperties.getInt("https.port", 8443);
        String contextPathProp = mirthProperties.getString("http.contextpath", "");

        // Add a starting slash if one does not exist
        if (!contextPathProp.startsWith("/")) {
            contextPathProp = "/" + contextPathProp;
        }

        // Remove a trailing slash if one exists
        if (contextPathProp.endsWith("/")) {
            contextPathProp = contextPathProp.substring(0, contextPathProp.length() - 1);
        }

        server = "https://" + serverHostname + ":" + httpsPort + contextPathProp;
    }

    jnlpElement.setAttribute("codebase", codebase);

    Element resourcesElement = (Element) jnlpElement.getElementsByTagName("resources").item(0);

    String maxHeapSize = request.getParameter("maxHeapSize");
    if (StringUtils.isBlank(maxHeapSize)) {
        maxHeapSize = mirthProperties.getString("administrator.maxheapsize");
    }
    if (StringUtils.isNotBlank(maxHeapSize)) {
        Element j2se = (Element) resourcesElement.getElementsByTagName("j2se").item(0);
        j2se.setAttribute("max-heap-size", maxHeapSize);
    }

    List<String> defaultClientLibs = new ArrayList<String>();
    defaultClientLibs.add("mirth-client.jar");
    defaultClientLibs.add("mirth-client-core.jar");
    defaultClientLibs.add("mirth-crypto.jar");
    defaultClientLibs.add("mirth-vocab.jar");

    for (String defaultClientLib : defaultClientLibs) {
        Element jarElement = document.createElement("jar");
        jarElement.setAttribute("download", "eager");
        jarElement.setAttribute("href", "webstart/client-lib/" + defaultClientLib);

        if (defaultClientLib.equals("mirth-client.jar")) {
            jarElement.setAttribute("main", "true");
        }

        resourcesElement.appendChild(jarElement);
    }

    List<String> clientLibs = ControllerFactory.getFactory().createExtensionController().getClientLibraries();

    for (String clientLib : clientLibs) {
        if (!defaultClientLibs.contains(clientLib)) {
            Element jarElement = document.createElement("jar");
            jarElement.setAttribute("download", "eager");
            jarElement.setAttribute("href", "webstart/client-lib/" + clientLib);
            resourcesElement.appendChild(jarElement);
        }
    }

    List<MetaData> allExtensions = new ArrayList<MetaData>();
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getConnectorMetaData().values());
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getPluginMetaData().values());

    // we are using a set so that we don't have duplicates
    Set<String> extensionPathsToAddToJnlp = new HashSet<String>();

    for (MetaData extension : allExtensions) {
        if (doesExtensionHaveClientOrSharedLibraries(extension)) {
            extensionPathsToAddToJnlp.add(extension.getPath());
        }
    }

    for (String extensionPath : extensionPathsToAddToJnlp) {
        Element extensionElement = document.createElement("extension");
        extensionElement.setAttribute("href", "webstart/extensions/" + extensionPath + ".jnlp");
        resourcesElement.appendChild(extensionElement);
    }

    Element applicationDescElement = (Element) jnlpElement.getElementsByTagName("application-desc").item(0);
    Element serverArgumentElement = document.createElement("argument");
    serverArgumentElement.setTextContent(server);
    applicationDescElement.appendChild(serverArgumentElement);
    Element versionArgumentElement = document.createElement("argument");
    versionArgumentElement.setTextContent(version);
    applicationDescElement.appendChild(versionArgumentElement);

    String[] protocols = configurationController.getHttpsClientProtocols();
    String[] cipherSuites = configurationController.getHttpsCipherSuites();

    // Only add arguments for the protocols / cipher suites if they are non-default
    if (!Arrays.areEqual(protocols, MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS)
            || !Arrays.areEqual(cipherSuites, MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES)) {
        Element sslArgumentElement = document.createElement("argument");
        sslArgumentElement.setTextContent("-ssl");
        applicationDescElement.appendChild(sslArgumentElement);

        Element protocolsArgumentElement = document.createElement("argument");
        protocolsArgumentElement.setTextContent(StringUtils.join(protocols, ','));
        applicationDescElement.appendChild(protocolsArgumentElement);

        Element cipherSuitesArgumentElement = document.createElement("argument");
        cipherSuitesArgumentElement.setTextContent(StringUtils.join(cipherSuites, ','));
        applicationDescElement.appendChild(cipherSuitesArgumentElement);
    }

    return document;
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Builds the base URL for the request that came in. This is everything up
 * to our web applications base, e.g. "http://localhost:8080/omh".
 * /*from  www .j av a  2 s  .c om*/
 * @param httpRequest
 *        The original HTTP request.
 * 
 * @return The base URL for the request.
 */
private String buildRootUrl(final HttpServletRequest httpRequest) {
    // It must be a HTTP request.
    StringBuilder builder = new StringBuilder("http");

    // If security was used add the "s" to make it "https".
    if (httpRequest.isSecure()) {
        builder.append('s');
    }

    // Add the protocol separator.
    builder.append("://");

    // Add the name of the server where the request was sent.
    builder.append(httpRequest.getServerName());

    // Add the port separator and the port.
    builder.append(':').append(httpRequest.getServerPort());

    // Add the context path, e.g. "/omh".
    builder.append(httpRequest.getContextPath());

    // Return the root URL.
    return builder.toString();
}

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureRequestServlet.java

@SuppressWarnings("unchecked")
@Override//from w w  w  .  j ava2 s . c o m
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doGet");

    String signatureRequest = (String) request.getSession().getAttribute(this.signatureRequestSessionAttribute);
    String signatureRequestId = (String) request.getSession()
            .getAttribute(this.signatureRequestIdSessionAttribute);
    String contentType = (String) request.getSession().getAttribute(this.contentTypeSessionAttribute);

    String dssDestination;
    String relayState;
    KeyStore.PrivateKeyEntry spIdentity = null;
    String language;

    SignatureRequestService service = this.signatureRequestServiceServiceLocator.locateService();
    if (null != service) {
        dssDestination = service.getDssDestination();
        relayState = service.getRelayState(request.getParameterMap());
        spIdentity = service.getSPIdentity();
        language = service.getLanguage();
    } else {
        dssDestination = this.target;
        relayState = (String) request.getSession().getAttribute(this.relayStateSessionAttribute);
        language = this.language;
    }

    // sp-destination
    String spDestination = null;
    if (null != service) {
        spDestination = service.getSPDestination();
    }
    if (null == spDestination) {
        // not provided by the service, check web.xml...
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
    }

    // generate and send a signature request
    try {
        SignatureRequestUtil.sendRequest(signatureRequest, signatureRequestId, contentType, dssDestination,
                spDestination, relayState, spIdentity, response, language);
    } catch (Exception e) {
        throw new ServletException(e);
    }

    // save state on session
    if (null != relayState) {
        setRelayState(relayState, request.getSession());
    }
    setTarget(spDestination, request.getSession());

}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public CFMLFactory getCFMLFactory(ServletConfig srvConfig, HttpServletRequest req) throws ServletException {
    ServletContext srvContext = srvConfig.getServletContext();

    String real = ReqRspUtil.getRootPath(srvContext);
    ConfigServerImpl cs = getConfigServerImpl();

    // Load JspFactory

    CFMLFactory factory = contextes.get(real);
    if (factory == null) {
        factory = initContextes.get(real);
        if (factory == null) {
            factory = loadJSPFactory(cs, srvConfig, initContextes.size());
            initContextes.put(real, factory);
        }//from  ww w  .ja v  a  2 s . c  o  m
        contextes.put(real, factory);

        try {
            String cp = req.getContextPath();
            if (cp == null)
                cp = "";
            ((CFMLFactoryImpl) factory)
                    .setURL(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), cp));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    return factory;
}

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:com.groupon.odo.Proxy.java

/**
 * Execute a redirected request//from   w ww.  j a v  a2s  . c  o  m
 *
 * @param stringStatusCode
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @throws Exception
 */
private void processRedirect(String stringStatusCode, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    // Check if the proxy response is a redirect
    // The following code is adapted from
    // org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software

    String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
    if (stringLocation == null) {
        throw new ServletException("Received status code: " + stringStatusCode + " but no "
                + STRING_LOCATION_HEADER + " header was found in the response");
    }
    // Modify the redirect to go to this proxy servlet rather than the proxied host
    String stringMyHostName = httpServletRequest.getServerName();
    if (httpServletRequest.getServerPort() != 80) {
        stringMyHostName += ":" + httpServletRequest.getServerPort();
    }
    stringMyHostName += httpServletRequest.getContextPath();
    httpServletResponse.sendRedirect(
            stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
}

From source file:flex.messaging.services.http.proxy.SecurityFilter.java

private void setCredentials(ProxyContext context) {
    String user = null, password = null;

    // Check for credentials in runAs
    user = context.getTarget().getRemoteUsername();
    password = context.getTarget().getRemotePassword();

    String fromRequest = null;/*from   w  w  w. j ava2  s . c  om*/
    HttpServletRequest clientRequest = FlexContext.getHttpRequest();
    if (clientRequest != null) {
        // Check for credentials in parameter/header
        fromRequest = clientRequest.getHeader(ProxyConstants.HEADER_CREDENTIALS);
    }

    // We sometimes send the credentials as a URL parameter to work around a player/Opera issue
    if (fromRequest == null) {
        fromRequest = context.getCredentialsHeader();
    }

    // Add authentication header for credentials
    if (fromRequest != null) {
        Base64.Decoder decoder = new Base64.Decoder();
        decoder.decode(fromRequest);
        String decoded = new String(decoder.drain());
        int colonIdx = decoded.indexOf(":");
        if (colonIdx != -1) {
            user = decoded.substring(0, colonIdx);
        }
        password = decoded.substring(colonIdx + 1);
    }

    // Check for existing authentication header
    if (clientRequest != null) {
        Enumeration headers = clientRequest.getHeaders("Authorization");
        if (headers != null) {
            while (headers.hasMoreElements()) {
                String value = (String) headers.nextElement();

                if (value.startsWith("Basic")) {
                    if (!context.isLocalDomainAndPort()) {
                        if (Log.isInfo()) {
                            Log.getLogger(HTTPProxyService.LOG_CATEGORY)
                                    .debug("Not sending on Authentication header. Proxy domain:port of "
                                            + clientRequest.getServerName() + ":"
                                            + clientRequest.getServerPort()
                                            + " does not match target domain:port of "
                                            + context.getTarget().getUrl().getHost() + ":"
                                            + context.getTarget().getUrl().getPort());
                        }
                    } else {
                        // Super gross hack to work around what appears to be an commons-httpclient bug
                        // where headers are not resent after a 302.
                        Base64.Decoder decoder = new Base64.Decoder();
                        String encoded = value.substring(6);
                        decoder.decode(encoded);
                        String decoded = new String(decoder.drain());
                        int colonIdx = decoded.indexOf(":");
                        user = decoded.substring(0, colonIdx);
                        password = decoded.substring(colonIdx + 1);
                    }
                }
            }
        }
    }

    // Set up request for authentication
    if (user != null) {
        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, password);

        context.getHttpClient().getState().setCredentials(ProxyUtil.getDefaultAuthScope(), cred);
        context.setAuthorization(true);

        if (Log.isInfo()) {
            Log.getLogger(HTTPProxyService.LOG_CATEGORY)
                    .info("-- Authentication header being sent for " + user);
        }
    }
}