Example usage for javax.servlet.http HttpServletRequest getServerName

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

Introduction

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

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

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  w  ww .j av a 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:com.janrain.backplane.server.Backplane1Controller.java

@RequestMapping(value = "/{version}/bus/{bus}/channel/{channel}", method = RequestMethod.POST)
public @ResponseBody String postToChannel(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String version,
        @RequestHeader(value = "Authorization", required = false) String basicAuth,
        @RequestBody List<Map<String, Object>> messages, @PathVariable String bus, @PathVariable String channel)
        throws AuthException, SimpleDBException, BackplaneServerException {

    User user = checkAuth(basicAuth, bus, BusConfig1.BUS_PERMISSION.POST);

    final TimerContext context = postMessagesTime.time();

    try {/* w  w  w .  j  a v a  2  s.c om*/

        RedisBackplaneMessageDAO backplaneMessageDAO = DaoFactory.getBackplaneMessageDAO();

        //Block post if the caller has exceeded the message post limit
        if (backplaneMessageDAO.getMessageCount(bus, channel) >= bpConfig.getDefaultMaxMessageLimit()) {
            logger.warn("Channel " + bus + ":" + channel + " has reached the maximum of "
                    + bpConfig.getDefaultMaxMessageLimit() + " messages");
            throw new BackplaneServerException("Message limit exceeded for this channel");
        }

        BusConfig1 busConfig = DaoFactory.getBusDAO().get(bus);

        // For analytics.
        String channelId = "https://" + request.getServerName() + "/" + version + "/bus/" + bus + "/channel/"
                + channel;
        String clientId = user.getIdValue();

        for (Map<String, Object> messageData : messages) {
            BackplaneMessage message = new BackplaneMessage(bus, channel, busConfig.getRetentionTimeSeconds(),
                    busConfig.getRetentionTimeStickySeconds(), messageData);
            backplaneMessageDAO.persist(message);
            aniLogNewMessage(version, bus, channelId, clientId);
        }

        return "";

    } finally {
        context.stop();
    }
}

From source file:com.ah.be.common.NmsUtil.java

/**
 * The function will return the web application url String with http (not https)
 *
 * @param request -//from w  ww  .j  a va  2 s.  co m
 * @return -
 */
public static String getWebAppHttpUrl(HttpServletRequest request) {
    String httpUrl;
    if (useHttpProxy) {
        // with proxy setting, the url will be hard coded
        httpUrl = "http://" + request.getServerName() + ":8080" + request.getContextPath() + "/";
    } else {
        // rewrite by the request information
        if ("https".equals(request.getScheme())) {
            if (request.getServerPort() == 8443) {
                httpUrl = "http://" + request.getServerName() + ":8080" + request.getContextPath() + "/";
            } else {
                httpUrl = "http://" + request.getServerName() + request.getContextPath() + "/";
            }
        } else {
            httpUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath() + "/";
        }
    }
    log.info("getWebAppHttpUrl", httpUrl);
    return httpUrl;
}

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

@SuppressWarnings("unchecked")
@Override//  w  ww .  j av  a 2  s .  com
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: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:edu.cornell.mannlib.vitro.webapp.controller.grefine.JSONReconcileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doGet(req, resp);
    resp.setContentType("application/json");
    VitroRequest vreq = new VitroRequest(req);

    try {/*ww  w  . j a v  a2 s.  co  m*/
        if (vreq.getParameter("query") != null || vreq.getParameter("queries") != null) {
            JSONObject qJson = getResult(vreq, req, resp);
            log.debug("result: " + qJson.toString());
            String responseStr = (vreq.getParameter("callback") == null) ? qJson.toString()
                    : vreq.getParameter("callback") + "(" + qJson.toString() + ")";
            // System.out.println("JSONReconcileServlet result: " + responseStr);
            ServletOutputStream out = resp.getOutputStream();
            out.print(responseStr);
        } else { // metadata
            String defaultNamespace = null;
            String defaultTypeList = null;
            String serverName = null;
            int serverPort = req.getServerPort();

            if (vreq.getWebappDaoFactory() != null) {
                defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace();
            }
            defaultTypeList = ConfigurationProperties.getBean(req)
                    .getProperty("Vitro.reconcile.defaultTypeList");
            serverName = req.getServerName();
            JSONObject metaJson = getMetadata(req, resp, defaultNamespace, defaultTypeList, serverName,
                    serverPort);
            String callbackStr = (vreq.getParameter("callback") == null) ? "" : vreq.getParameter("callback");
            ServletOutputStream out = resp.getOutputStream();
            out.print(callbackStr + "(" + metaJson.toString() + ")");
        }
    } catch (Exception ex) {
        log.warn(ex, ex);
    }
}

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);
        }/* ww  w.  j  av a2  s . c om*/
        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: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;//w w  w  . j  a  va  2  s. co m
    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);
        }
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * Execute a redirected request/*from  ww  w.  j ava  2 s  . 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:org.ngrinder.script.controller.SvnDavController.java

@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());/*from w w w  .  j  a v  a2  s .  c  o m*/
}