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.linkcm.core.sso.CasAuthenticationEntryPoint.java

public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
        final AuthenticationException authenticationException) throws IOException, ServletException {
    StringBuilder tempLoginUrl = new StringBuilder();
    StringBuilder serverUrl = new StringBuilder();
    StringBuilder clientUrl = new StringBuilder();

    tempLoginUrl.append(servletRequest.getScheme()).append("://");
    tempLoginUrl.append(servletRequest.getServerName());

    if (serverPort != null && !"".equals(serverPort)) {
        serverUrl.append(tempLoginUrl).append(":").append(serverPort);
    }/* w w  w.j  a v a2s .c o  m*/
    serverUrl.append("/cas/login");
    loginUrl = serverUrl.toString();

    if (clientPort != null && !"".equals(clientPort)) {
        clientUrl.append(tempLoginUrl).append(":").append(servletRequest.getServerPort());
        clientUrl.append(servletRequest.getContextPath());
        clientUrl.append("/j_spring_cas_security_check");
        serviceProperties.setService(clientUrl.toString());
    }

    final String urlEncodedService = createServiceUrl(servletRequest, response);
    final String redirectUrl = createRedirectUrl(urlEncodedService);

    preCommence(servletRequest, response);
    response.sendRedirect(redirectUrl);
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

private String getEntityId(HttpServletRequest request) {
    return request.getScheme() + "://saml." + request.getServerName();
}

From source file:com.frameworkset.platform.cms.driver.url.impl.CMSURLParserImpl.java

/**
 * Parse a servlet request to a portal URL.
 * @param request  the servlet request to parse.
 * @return the portal URL.//from   w w  w.j  ava  2s .  co  m
 */
public CMSURL parse(HttpServletRequest request) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing URL: " + request.getRequestURI());
    }

    String protocol = request.isSecure() ? "https://" : "http://";
    String server = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getContextPath();
    String servletName = request.getServletPath();

    // Construct portal URL using info retrieved from servlet request.
    CMSURL portalURL = null;
    if ((request.isSecure() && port != 443) || (!request.isSecure() && port != 80)) {
        portalURL = new CMSURLImpl(protocol, server, port, contextPath, servletName);
    } else {
        portalURL = new CMSURLImpl(protocol, server, contextPath, servletName);
    }

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return portalURL;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing request pathInfo: " + pathInfo);
    }
    StringBuffer renderPath = new StringBuffer();
    StringTokenizer st = new StringTokenizer(pathInfo, "/", false);
    while (st.hasMoreTokens()) {

        String token = st.nextToken();

        // Part of the render path: append to renderPath.
        if (!token.startsWith(PREFIX)) {
            //              renderPath.append(token);
            //Fix for PLUTO-243
            renderPath.append('/').append(token);
        }
        // Action window definition: portalURL.setActionWindow().
        else if (token.startsWith(PREFIX + ACTION)) {
            portalURL.setActionWindow(decodeControlParameter(token)[0]);
        }
        // Window state definition: portalURL.setWindowState().
        else if (token.startsWith(PREFIX + WINDOW_STATE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setWindowState(decoded[0], new WindowState(decoded[1]));
        }
        // Portlet mode definition: portalURL.setPortletMode().
        else if (token.startsWith(PREFIX + PORTLET_MODE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setPortletMode(decoded[0], new PortletMode(decoded[1]));
        }
        // Portal URL parameter: portalURL.addParameter().
        else {
            String value = null;
            if (st.hasMoreTokens()) {
                value = st.nextToken();
            }
            portalURL.addParameter(decodeParameter(token, value));
        }
    }
    if (renderPath.length() > 0) {
        portalURL.setRenderPath(renderPath.toString());
    }

    // Return the portal URL.
    return portalURL;
}

From source file:com.wisemapping.mail.NotificationService.java

private void sendNotification(@NotNull Map<String, String> model, @Nullable User user,
        @NotNull HttpServletRequest request) {
    model.put("fullName", (user != null ? user.getFullName() : "'anonymous'"));
    final String userEmail = user != null ? user.getEmail() : "'anonymous'";

    model.put("email", userEmail);
    model.put("userAgent", request.getHeader(SupportedUserAgent.USER_AGENT_HEADER));
    model.put("server", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort());
    model.put("requestURI", request.getRequestURI());
    model.put("method", request.getMethod());
    model.put("remoteAddress", request.getRemoteAddr());

    try {//from w ww  .ja  va2  s .  c om
        final String errorReporterEmail = mailer.getErrorReporterEmail();
        if (errorReporterEmail != null && !errorReporterEmail.isEmpty()) {

            if (!notificationFilter.hasBeenSend(userEmail, model)) {
                mailer.sendEmail(mailer.getServerSenderEmail(), errorReporterEmail,
                        "[WiseMapping] Bug from '" + (user != null ? user.getEmail() + "'" : "'anonymous'"),
                        model, "errorNotification.vm");
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:com.liferay.portal.util.PortalUtil.java

public static String getPortalURL(HttpServletRequest req, boolean secure) {
    StringBuffer sb = new StringBuffer();

    String serverProtocol = GetterUtil.getString(PropsUtil.get(PropsUtil.WEB_SERVER_PROTOCOL));

    if (secure || Http.HTTPS.equals(serverProtocol)) {
        sb.append(Http.HTTPS_WITH_SLASH);
    } else {//www . j a v  a2 s  .co m
        sb.append(Http.HTTP_WITH_SLASH);
    }

    String serverHost = PropsUtil.get(PropsUtil.WEB_SERVER_HOST);

    if (Validator.isNull(serverHost)) {
        sb.append(req.getServerName());
    } else {
        sb.append(serverHost);
    }

    int serverHttpPort = GetterUtil.get(PropsUtil.get(PropsUtil.WEB_SERVER_HTTP_PORT), -1);

    if (serverHttpPort == -1) {
        if (!secure && (req.getServerPort() != Http.HTTP_PORT)) {
            sb.append(StringPool.COLON).append(req.getServerPort());
        }
    } else {
        if (!secure && (req.getServerPort() != serverHttpPort)) {
            if (serverHttpPort != Http.HTTP_PORT) {
                sb.append(StringPool.COLON).append(serverHttpPort);
            }
        }
    }

    int serverHttpsPort = GetterUtil.get(PropsUtil.get(PropsUtil.WEB_SERVER_HTTPS_PORT), -1);

    if (serverHttpsPort == -1) {
        if (secure && (req.getServerPort() != Http.HTTPS_PORT)) {
            sb.append(StringPool.COLON).append(req.getServerPort());
        }
    } else {
        if (secure && (req.getServerPort() != serverHttpsPort)) {
            if (serverHttpsPort != Http.HTTPS_PORT) {
                sb.append(StringPool.COLON).append(serverHttpsPort);
            }
        }
    }

    return sb.toString();
}

From source file:com.hortonworks.registries.auth.server.TestKerberosAuthenticationHandler.java

public void testRequestWithAuthorization() throws Exception {
    String token = KerberosTestUtils.doAsClient(new Callable<String>() {
        @Override/*from  w  w w .  ja  v a2  s  .c o  m*/
        public String call() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext gssContext = null;
            try {
                String servicePrincipal = KerberosTestUtils.getServerPrincipal();
                Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);

                byte[] inToken = new byte[0];
                byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                Base64 base64 = new Base64(0);
                return base64.encodeToString(outToken);

            } finally {
                if (gssContext != null) {
                    gssContext.dispose();
                }
            }
        }
    });

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);
    Mockito.when(request.getServerName()).thenReturn("localhost");

    AuthenticationToken authToken = handler.authenticate(request, response);

    if (authToken != null) {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

        Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
        Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
        Assert.assertEquals(getExpectedType(), authToken.getType());
    } else {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.rometools.propono.atom.server.impl.FileBasedAtomHandler.java

/**
 * Contruct handler for one request, using specified file storage directory.
 *
 * @param req Request to be handled.//from  w  w  w. j  av  a  2  s  .c  o  m
 * @param uploaddir File storage upload dir.
 */
public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) {
    LOG.debug("ctor");

    userName = authenticateBASIC(req);

    atomProtocolURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath() + req.getServletPath();

    contextURI = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();

    try {
        service = new FileBasedAtomService(userName, uploaddir, contextURI, req.getContextPath(),
                req.getServletPath());
    } catch (final Throwable t) {
        throw new RuntimeException("ERROR creating FileBasedAtomService", t);
    }
}

From source file:com.baoqilai.core.sso.CasAuthenticationEntryPoint.java

public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
        final AuthenticationException authenticationException) throws IOException, ServletException {
    StringBuilder tempLoginUrl = new StringBuilder();
    StringBuilder serverUrl = new StringBuilder();
    StringBuilder clientUrl = new StringBuilder();
    System.out.println("???");
    tempLoginUrl.append(servletRequest.getScheme()).append("://");
    tempLoginUrl.append(servletRequest.getServerName());

    if (serverPort != null && !"".equals(serverPort)) {
        serverUrl.append(tempLoginUrl).append(":").append(serverPort);
    }/*from w ww . j  a  va 2s  . c o  m*/
    serverUrl.append("/cas/login");
    loginUrl = serverUrl.toString();

    if (clientPort != null && !"".equals(clientPort)) {
        clientUrl.append(tempLoginUrl).append(":").append(servletRequest.getServerPort());
        clientUrl.append(servletRequest.getContextPath());
        clientUrl.append("/j_spring_cas_security_check");
        serviceProperties.setService(clientUrl.toString());
    }

    final String urlEncodedService = createServiceUrl(servletRequest, response);
    final String redirectUrl = createRedirectUrl(urlEncodedService);

    preCommence(servletRequest, response);
    response.sendRedirect(redirectUrl);
}

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // ping publish
    // wait for notification
    // response//  w  ww.j  a  v  a 2 s  . c  o m
    // error if timeout

    if (req.getPathInfo().equals("/feed")) {
        // serve ATOM feed
        resp.getWriter().write(atom(getFragment(req)));
    } else {
        // publish

        UUID id = UUID.randomUUID();
        String publicationUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/feed#" + id;

        String hubUrl = System.getProperty("hub.url");
        if (hubUrl == null) {
            throw new RuntimeException("System properti hub.url missing");
        }

        try {
            CountDownLatch latch = new CountDownLatch(1);
            publications.put(id, latch);

            HttpPost publication = new HttpPost(hubUrl);
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("hub.mode", "publish"));
            parameters.add(new BasicNameValuePair("hub.url", publicationUrl));

            publication.setEntity(new UrlEncodedFormEntity(parameters));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse publicationResponse = httpClient.execute(publication);

            if (publicationResponse.getStatusLine().getStatusCode() == 204) {
                try {
                    if (latch.await(20000, TimeUnit.MILLISECONDS)) {
                        // all happy, return
                        return;
                    } else {
                        // timeout
                        resp.sendError(591);
                    }
                } catch (InterruptedException e) {
                    // interrupted
                    resp.sendError(592);
                }
            } else {
                // publication failed
                resp.sendError(publicationResponse.getStatusLine().getStatusCode(),
                        publicationResponse.getStatusLine().getReasonPhrase());
            }
        } finally {
            // try to prevent memory leaks
            publications.remove(id);
        }
    }
}

From source file:br.com.flucianofeijao.security.JsfLoginUrlAuthenticationEntryPoint.java

/**
 * Builds a URL to redirect the supplied request to HTTPS. Used to redirect the current request
 * to HTTPS, before doing a forward to the login page.
 *///  w  ww.  jav  a2s .co  m
protected String buildHttpsRedirectUrlForRequest(HttpServletRequest request)
        throws IOException, ServletException {

    int serverPort = portResolver.getServerPort(request);
    Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));

    if (httpsPort != null) {
        RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
        urlBuilder.setScheme("https");
        urlBuilder.setServerName(request.getServerName());
        urlBuilder.setPort(httpsPort.intValue());
        urlBuilder.setContextPath(request.getContextPath());
        urlBuilder.setServletPath(request.getServletPath());
        urlBuilder.setPathInfo(request.getPathInfo());
        urlBuilder.setQuery(request.getQueryString());

        return urlBuilder.getUrl();
    }

    // Fall through to server-side forward with warning message
    logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);

    return null;
}