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.enonic.cms.web.main.UpgradeController.java

/**
 * Return the base path./*from  w w w  . j a  v a2  s. com*/
 */
private String createBaseUrl(HttpServletRequest req) {
    StringBuffer str = new StringBuffer();
    str.append(req.getScheme()).append("://").append(req.getServerName());

    if (req.getServerPort() != 80) {
        str.append(":").append(req.getServerPort());
    }

    str.append(req.getContextPath());
    return str.toString();
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Handle request for sending mails when a user create a project
 * and invite friends to become members.
 * //from  w  w  w . j  a v  a2  s  . c o  m
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 * 
 */
@RequestMapping(value = "/joinProject", method = RequestMethod.POST)
public String inviteToJoinProject(@RequestParam(required = false) String recepientEmailIds,
        @RequestParam(required = false) String otherInfoString, Locale locale, HttpServletRequest req)
        throws IdeasExchangeException, AddressException, MessagingException {
    String serverName = req.getServerName();
    String projectKey;
    String ownerName;
    String projectName;
    if (otherInfoString != null) {
        /* getting data which are required for sending mail. */
        String infoData[] = otherInfoString.split(COMMA);
        if (infoData.length > TWO) {
            ownerName = infoData[ZERO];
            projectName = infoData[ONE];
            projectKey = infoData[TWO];
            /* Iterating through all mail ids and sending messages. */
            for (String emailIdAndName : recepientEmailIds.split(COMMA)) {
                String info[] = emailIdAndName.split(SEMICOLON);
                if (info.length > TWO) {
                    String displayName = info[ONE];
                    String emailId = info[ZERO];
                    String developerKey = info[TWO];
                    String[] message = getMessageToSend(projectKey, ownerName, projectName, displayName,
                            developerKey, emailId, serverName);
                    String emailText = messageSource.getMessage(MAIL_PROJECT_INVITE_KEY, message, locale);
                    log.info("Sending Mail to : " + emailId + " Text: " + emailText);
                    sendMail(emailId, emailText, PROJECT_INVITE_MAIL_SUBJECT);
                }
            }
        }
    }
    return "queue/queue";
}

From source file:org.mla.cbox.shibboleth.idp.authn.impl.InitializeTwitterContext.java

@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {

    /* Create a new TwitterContext */
    final TwitterContext twitterContext = new TwitterContext();

    /* Set the Twitter integration details for the context */
    twitterContext.setTwitterIntegration(this.twitterIntegration);
    log.debug("{} Created TwitterContext using TwitterIntegration with consumer key {}", getLogPrefix(),
            this.twitterIntegration.getOauthConsumerKey());

    /* Create a new Twitter class instance and add it to the context */
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(this.twitterIntegration.getOauthConsumerKey(),
            this.twitterIntegration.getOauthConsumerSecret());
    twitterContext.setTwitter(twitter);/*from   ww w. j a v  a 2 s. c  o m*/

    /* Find the Spring context and from it the current flow execution URL */
    SpringRequestContext springRequestContext = (SpringRequestContext) profileRequestContext
            .getSubcontext(SpringRequestContext.class);
    RequestContext requestContext = springRequestContext.getRequestContext();
    String flowUrl = requestContext.getFlowExecutionUrl();

    /* Construct the callback URL using the flow execution URL and the server details */
    ServletExternalContext externalContext = (ServletExternalContext) requestContext.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getNativeRequest();
    StringBuilder callbackUrlBuilder = new StringBuilder().append(request.getScheme()).append("://")
            .append(request.getServerName()).append(flowUrl).append("&_eventId=proceed");

    String callbackUrl = callbackUrlBuilder.toString();

    /* Query Twitter for the request token and include the callback URL */
    try {
        log.debug("{} Obtaining request token with callback URL {}", getLogPrefix(), callbackUrl);
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
        twitterContext.setRequestToken(requestToken);
        log.debug("{} Obtained request token", getLogPrefix());
    } catch (TwitterException e) {
        log.error("{} Error obtaining request token from Twitter: {}", getLogPrefix(), e.getErrorMessage());
        ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS);
        return;
    }

    /* Save the context as a sub context to the authentication context */
    authenticationContext.addSubcontext(twitterContext, true);

    return;
}

From source file:se.vgregion.mobile.controllers.AdminGuiController.java

private URI getApplicationUrl(HttpServletRequest request) {
    if (applicationUrl != null) {
        return applicationUrl;
    } else {/*from  w  w  w. j  a v  a2s  .c  o  m*/
        StringBuilder sb = new StringBuilder();
        sb.append(request.getScheme());
        sb.append("://");
        sb.append(request.getServerName());
        if (request.getServerPort() > 0) {
            sb.append(":");
            sb.append(request.getServerPort());
        }
        sb.append(request.getContextPath());

        return URI.create(sb.toString());
    }
}

From source file:com.ge.predix.uaa.token.lib.ZacTokenServiceTest.java

@SuppressWarnings("unchecked")
private OAuth2Authentication loadAuthentication(final String zoneName, final String zoneUserScope,
        final String requestUri, final List<String> nonZoneUriPatterns) {

    ZacTokenService zacTokenServices = new ZacTokenService();
    zacTokenServices.setServiceZoneHeaders(PREDIX_ZONE_HEADER_NAME);

    Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(zoneUserScope));

    OAuth2Authentication oauth2Authentication = Mockito.mock(OAuth2Authentication.class);

    Mockito.when(oauth2Authentication.isAuthenticated()).thenReturn(true);
    FastTokenServices mockFTS = Mockito.mock(FastTokenServices.class);
    Mockito.doNothing().when(mockFTS).setUseHttps(true);
    Mockito.doNothing().when(mockFTS).setStoreClaims(true);
    Mockito.doNothing().when(mockFTS).setTrustedIssuers(Matchers.anyList());
    Mockito.when(oauth2Authentication.getAuthorities()).thenReturn(authorities);
    Mockito.when(mockFTS.loadAuthentication(Matchers.anyString())).thenReturn(oauth2Authentication);

    FastTokenServicesCreator mockFTSC = Mockito.mock(FastTokenServicesCreator.class);
    when(mockFTSC.newInstance()).thenReturn(mockFTS);

    zacTokenServices.setFastRemoteTokenServicesCreator(mockFTSC);
    zacTokenServices.setServiceBaseDomain(BASE_DOMAIN);
    zacTokenServices.setServiceId(SERVICEID);

    DefaultZoneConfiguration zoneConfig = new DefaultZoneConfiguration();

    List<String> trustedIssuers;
    // Non zone specific request, using default issuer
    if (StringUtils.isEmpty(zoneName)) {
        trustedIssuers = Arrays.asList(DEFAULT_TRUSTED_ISSUER);
        // Zone specific request, using the issuers returned by mockTrustedIssuersResponseEntity
    } else {// w w  w . ja  va 2 s.  c  om
        trustedIssuers = ZONE_TRUSTED_ISSUERS;
    }
    zoneConfig.setTrustedIssuerIds(trustedIssuers);
    zacTokenServices.setDefaultZoneConfig(zoneConfig);
    zoneConfig.setAllowedUriPatterns(nonZoneUriPatterns);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    when(request.getServerName()).thenReturn("localhost");
    when(request.getHeader(PREDIX_ZONE_HEADER_NAME)).thenReturn(zoneName);
    when(request.getRequestURI()).thenReturn(requestUri);
    zacTokenServices.setRequest(request);
    RestTemplate restTemplateMock = Mockito.mock(RestTemplate.class);
    zacTokenServices.setOauth2RestTemplate(restTemplateMock);
    try {
        zacTokenServices.afterPropertiesSet();
    } catch (Exception e) {
        Assert.fail("Unexpected exception after properties set on zacTokenServices " + e.getMessage());
    }

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + ZONE, TrustedIssuers.class))
            .thenReturn(mockTrustedIssuersResponseEntity());

    when(restTemplateMock.getForEntity("null/v1/registration/" + SERVICEID + "/" + INVALID_ZONE,
            TrustedIssuers.class)).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));

    String accessToken = this.tokenUtil.mockAccessToken(600, zoneUserScope);
    OAuth2Authentication loadAuthentication = zacTokenServices.loadAuthentication(accessToken);

    // Making sure we are passing the right set of issuers to the FastTokenServices
    Mockito.verify(mockFTS).setTrustedIssuers(trustedIssuers);
    return loadAuthentication;
}

From source file:com.jaeksoft.searchlib.web.AbstractServlet.java

private void buildUrls(HttpServletRequest request) throws MalformedURLException {
    serverBaseURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
            request.getContextPath()).toString();
    StringBuilder sbUrl = new StringBuilder(request.getRequestURI());
    String qs = request.getQueryString();
    if (qs != null) {
        sbUrl.append('?');
        sbUrl.append(qs);//from   w  w w .  j  av  a 2  s .  c  o  m
    }
    URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), sbUrl.toString());
    serverURL = url.toString();
}

From source file:edu.wisc.my.redirect.TabSelectingUrlRedirectController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    final String serverName = request.getServerName();
    final PortalUrl portalUrl = this.portalUrlProvider.getPortalUrl(serverName);

    //If strict param matching only run if the request parameter keyset matches the mapped parameter keyset
    final Set<?> requestParameterKeys = request.getParameterMap().keySet();
    if (this.strictParameterMatching && !requestParameterKeys.equals(this.parameterMappings.keySet())) {
        if (this.logger.isInfoEnabled()) {
            this.logger.info("Sending not found error, requested parameter key set " + requestParameterKeys
                    + " does not match mapped parameter key set " + this.parameterMappings.keySet());
        }/*from  www  . j a  v a2  s  . co m*/

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    //Map static parameters
    for (final Map.Entry<String, List<String>> parameterMappingEntry : this.staticParameters.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final List<String> values = parameterMappingEntry.getValue();

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Adding static parameter '" + name + "' with values: " + values);
        }

        portalUrl.setParameter(name, values.toArray(new String[values.size()]));
    }

    //Map request parameters
    for (final Map.Entry<String, Set<String>> parameterMappingEntry : this.parameterMappings.entrySet()) {
        final String name = parameterMappingEntry.getKey();
        final String[] values = request.getParameterValues(name);

        if (values != null) {
            for (final String mappedName : parameterMappingEntry.getValue()) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Mapping parameter '" + name + "' to portal parameter '" + mappedName
                            + "' with values: " + Arrays.asList(values));
                }

                portalUrl.setParameter(mappedName, values);
            }
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug(
                    "Skipping mapped parameter '" + name + "' since it was not specified on the original URL");
        }
    }

    //Set public based on if remoteUser is set
    final String remoteUser = request.getRemoteUser();
    final boolean isAuthenticated = StringUtils.isNotBlank(remoteUser);
    portalUrl.setPublic(!isAuthenticated);

    if (isAuthenticated) {
        portalUrl.setTabIndex(this.privateTabIndex);
    } else {
        portalUrl.setTabIndex(this.publicTabIndex);
    }

    portalUrl.setType(RequestType.ACTION);

    final String redirectUrl = portalUrl.toString();
    if (this.logger.isInfoEnabled()) {
        this.logger.info("Redirecting to: " + redirectUrl);
    }

    return new ModelAndView(new RedirectView(redirectUrl, false));
}

From source file:com.acc.storefront.controllers.pages.StoreLocatorPageController.java

@ModelAttribute("googleApiKey")
public String getGoogleApiKey(final HttpServletRequest request) {
    final String googleApiKey = getHostConfigService().getProperty(GOOGLE_API_KEY_ID, request.getServerName());
    if (StringUtils.isEmpty(googleApiKey)) {
        LOG.warn("No Google API key found for server: " + request.getServerName());
    }//w  w  w .  j  a  v a2s  .  co m
    return googleApiKey;
}

From source file:com.qcadoo.mes.integration.cfcSimple.IntegrationController.java

protected final String handleUpload(final HttpServletRequest request, final MultipartFile file,
        final Locale locale) {
    try {//from   w w w .  j av  a  2  s.c  om
        String redirect = getIntegrationPerformer().performImport(file.getInputStream());
        String context = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        return redirect.replaceAll("\\$\\{root\\}", context);
    } catch (IOException e) {
        throw new IllegalStateException("Error while reading file", e);
    }
}

From source file:com.twocharts.www.samples.apps.marketplace.OpenIdServlet.java

/**
 * Dynamically constructs the base URL for the application based on the current request
 *
 * @param request Current servlet request
 * @return Base URL (path to servlet context)
 *///from w w w .  jav  a  2 s . c  o  m
String baseUrl(HttpServletRequest request) {
    StringBuffer url = new StringBuffer(request.getScheme()).append("://").append(request.getServerName());

    if ((request.getScheme().equalsIgnoreCase("http") && request.getServerPort() != 80)
            || (request.getScheme().equalsIgnoreCase("https") && request.getServerPort() != 443)) {
        url.append(":").append(request.getServerPort());
    }

    return url.toString();
}