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.saint.spring.saml.web.MetadataController.java

protected String getBaseURL(HttpServletRequest request) {

    String baseURL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath();//from   w w  w.  j  a v a 2  s .  c  o  m
    log.debug("Base URL {}", baseURL);
    return baseURL;

}

From source file:org.onebusaway.webapp.actions.rss.TripProblemReportsAction.java

@Override
public String execute() {

    AgencyBean agency = _transitDataService.getAgency(_agencyId);

    if (agency == null)
        return INPUT;

    Calendar c = Calendar.getInstance();
    long timeTo = c.getTimeInMillis();
    c.add(Calendar.DAY_OF_WEEK, -_days);
    long timeFrom = c.getTimeInMillis();

    TripProblemReportQueryBean query = new TripProblemReportQueryBean();
    query.setAgencyId(_agencyId);// w w w. java 2  s  .co m
    query.setTimeFrom(timeFrom);
    query.setTimeTo(timeTo);
    if (_status != null)
        query.setStatus(EProblemReportStatus.valueOf(_status));
    query.setLabel(_label);

    ListBean<TripProblemReportBean> result = _transitDataService.getTripProblemReports(query);
    List<TripProblemReportBean> reports = result.getList();

    _feed = new SyndFeedImpl();

    StringBuilder title = new StringBuilder();
    title.append(getText("rss.OneBusAwayTripProblemReports"));
    title.append(" - ");
    title.append(agency.getName());
    title.append(" - ");
    title.append(getText("rss.LastXDays", Arrays.asList((Object) _days)));

    HttpServletRequest request = ServletActionContext.getRequest();

    StringBuilder b = new StringBuilder();
    b.append("http://");
    b.append(request.getServerName());
    if (request.getServerPort() != 80)
        b.append(":").append(request.getServerPort());
    if (request.getContextPath() != null)
        b.append(request.getContextPath());
    String baseUrl = b.toString();

    _feed.setTitle(title.toString());
    _feed.setLink(baseUrl);
    _feed.setDescription(
            getText("rss.UserSubmittedTripProblemReports", Arrays.asList((Object) agency.getName(), _days)));

    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    _feed.setEntries(entries);

    for (TripProblemReportBean report : reports) {

        StopBean stop = report.getStop();
        TripBean trip = report.getTrip();

        SyndEntry entry = new SyndEntryImpl();

        StringBuilder entryTitle = new StringBuilder();
        if (trip == null) {
            entryTitle.append("trip_id=");
            entryTitle.append(report.getTripId());
            entryTitle.append(" (?)");
        } else {
            entryTitle.append(RoutePresenter.getNameForRoute(trip));
            entryTitle.append(" - ");
            entryTitle.append(trip.getTripHeadsign());
        }
        if (stop == null) {
            entryTitle.append(" - stop_id=");
            entryTitle.append(report.getStopId());
            entryTitle.append(" (?)");
        } else {
            entryTitle.append(" - ");
            entryTitle.append(getText("StopNum", new String[] { stop.getCode() }));
            entryTitle.append(" - ");
            entryTitle.append(stop.getName());
            if (stop.getDirection() != null) {
                entryTitle.append(" - ");
                entryTitle.append(getText("bound", new String[] { stop.getDirection() }));
            }
        }

        StringBuilder entryUrl = new StringBuilder();
        entryUrl.append(baseUrl);
        entryUrl.append("/admin/problems/trip-problem-report.action?tripId=");
        entryUrl.append(report.getTripId());
        entryUrl.append("&id=");
        entryUrl.append(report.getId());

        StringBuilder entryDesc = new StringBuilder();
        entryDesc.append(getText("Data"));
        entryDesc.append(": ");
        entryDesc.append(report.getData());
        entryDesc.append("<br/>");

        if (report.getUserComment() != null) {
            entryDesc.append(getText("Comment"));
            entryDesc.append(": ");
            entryDesc.append(report.getUserComment());
            entryDesc.append("<br/>");
        }

        if (report.getStatus() != null) {
            entryDesc.append(getText("Status"));
            entryDesc.append(": ");
            entryDesc.append(report.getStatus());
            entryDesc.append("<br/>");
        }

        entry = new SyndEntryImpl();
        entry.setTitle(entryTitle.toString());
        entry.setLink(entryUrl.toString());
        entry.setPublishedDate(new Date(report.getTime()));

        SyndContent description = new SyndContentImpl();
        description.setType("text/html");
        description.setValue(entryDesc.toString());
        entry.setDescription(description);
        entries.add(entry);
    }

    return SUCCESS;
}

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

private void sendSecurityInfo(ProxyContext context) {
    Target target = context.getTarget();
    String targetHost = target.getUrl().getHost();

    int statusCode = 200;

    boolean customAuth = target.useCustomAuthentication();

    StatusLine statusLine = context.getHttpMethod().getStatusLine();
    if (statusLine != null) {
        statusCode = statusLine.getStatusCode();
    }/*  w  w  w  .j  a va2s  .  c o m*/

    context.setStatusCode(statusCode);

    if (statusCode == 401 || statusCode == 403) {
        if (!customAuth) {
            if (!context.isHttpRequest()) {
                throw new ProxyException(NO_BASIC_NOT_HTTP);
            } else if (context.isSoapRequest()) {
                // Note: if we remove this error, must do the proxyDomain/targetHost check as done above
                throw new ProxyException(NO_BASIC_FOR_SOAP);
            } else {
                // Don't allow a 401 (and 403, although this should never happen) to be sent to the client
                // if the service is not using custom authentication and the domains do not match

                if (!context.isLocalDomainAndPort()) {
                    HttpServletRequest clientRequest = FlexContext.getHttpRequest();

                    String errorMessage = ProxyConstants.DOMAIN_ERROR + " . The proxy domain:port is "
                            + clientRequest.getServerName() + ":" + clientRequest.getServerPort()
                            + " and the target domain:port is " + targetHost + ":" + target.getUrl().getPort();

                    Log.getLogger(HTTPProxyService.LOG_CATEGORY).error(errorMessage);

                    throw new ProxyException(DOMAIN_ERROR);
                } else {
                    //For BASIC Auth, send back the status code
                    HttpServletResponse clientResponse = FlexContext.getHttpResponse();
                    clientResponse.setStatus(statusCode);
                }
            }
        } else {
            String message = null;
            if (statusLine != null)
                message = statusLine.toString();

            if (statusCode == 401) {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(LOGIN_REQUIRED);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }

                Header header = context.getHttpMethod().getResponseHeader(ProxyConstants.HEADER_AUTHENTICATE);
                if (header != null)
                    se.setDetails(header.getValue());
                throw se;
            } else {
                ProxyException se = new ProxyException();
                se.setCode("Client.Authentication");
                if (message == null) {
                    se.setMessage(UNAUTHORIZED_ERROR);
                } else {
                    se.setMessage(EMPTY_ERROR, new Object[] { message });
                }
                throw se;
            }
        }
    }
}

From source file:io.fabric8.api.registry.ApiRegistryService.java

protected void checkForUrlPrefix() {
    if (urlPrefix == null && messageContext != null) {
        HttpServletRequest request = messageContext.getHttpServletRequest();
        ServletContext servletContext = messageContext.getServletContext();
        if (request != null && servletContext != null) {
            String swaggerPrefix = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort();
            String contextPath = servletContext.getContextPath();
            urlPrefix = urlPathJoin(swaggerPrefix, contextPath);
            finder.setUrlPrefix(urlPrefix);
        }/*from w  ww .  j a v a  2  s.c  o  m*/
    }

}

From source file:org.deegree.client.core.renderer.InputFileRenderer.java

private URL getUrl(HttpServletRequest request, String target, String fileName) throws MalformedURLException {
    if (target == null) {
        target = "";
    }/*w  w  w  . j a v  a  2  s.c o  m*/
    if (!target.startsWith("/")) {
        target = "/" + target;
    }
    if (!target.endsWith("/")) {
        target += "/";
    }
    return new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
            request.getContextPath() + target + fileName);
}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java

/**
 * Constructs an URL where the user is redirected for authentication.
 * @param flowExecutionUrl The current flow execution URL, to be included in the redirect URL.
 * @param authenticationContext The context, also containing {@link WilmaAuthenticationContext}.
 * @return The redirect URL containing the checksum.
 *///w w w  .j  ava  2s  . co m
public String getRedirect(final String flowExecutionUrl, final AuthenticationContext authenticationContext) {
    final HttpServletRequest httpRequest = getHttpServletRequest();
    final WilmaAuthenticationContext wilmaContext = authenticationContext
            .getSubcontext(WilmaAuthenticationContext.class);
    final StringBuffer redirectToBuffer = new StringBuffer(
            httpRequest.getScheme() + "://" + httpRequest.getServerName());
    if (httpRequest.getServerPort() != 443) {
        redirectToBuffer.append(":" + httpRequest.getServerPort());
    }
    redirectToBuffer.append(flowExecutionUrl).append(getAsParameter("&", "_eventId_proceed", "1"));
    redirectToBuffer
            .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_NONCE, wilmaContext.getNonce()));
    final URLCodec urlCodec = new URLCodec();
    try {
        final StringBuffer unsignedUrlBuffer = new StringBuffer(wilmaContext.getRedirectUrl());
        unsignedUrlBuffer.append(getAsParameter("?", WilmaAuthenticationContext.PARAM_NAME_REDIRECT_TO,
                urlCodec.encode(redirectToBuffer.toString())));
        if (authenticationContext.isForceAuthn()) {
            unsignedUrlBuffer
                    .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_FORCE_AUTH, "true"));
        }
        final String redirectUrl = unsignedUrlBuffer.toString() + getAsParameter("&",
                WilmaAuthenticationContext.PARAM_NAME_CHECKSUM,
                calculateChecksum(Mac.getInstance(algorithm), unsignedUrlBuffer.toString(), signatureKey));
        return redirectUrl;
    } catch (EncoderException | NoSuchAlgorithmException e) {
        log.error("{}: Could not encode the following URL {}", getLogPrefix(), redirectToBuffer, e);
    }
    return null;
}

From source file:org.alfresco.wcm.client.interceptor.ApplicationDataInterceptor.java

/**
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(HttpServletRequest,
 *      HttpServletResponse, Object)//from w ww  . j av a2 s. co m
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    RequestContext requestContext = ThreadLocalRequestContext.getRequestContext();

    // Get the website object and store it in the surf request context
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    WebSite webSite = webSiteService.getWebSite(serverName, serverPort, contextPath);

    if (webSite == null) {
        log.warn("Received request for which no configured website can be found: " + serverName + ":"
                + serverPort);
        throw new PageNotFoundException(serverName + ":" + serverPort);
    }

    WebSiteService.setThreadWebSite(webSite);
    requestContext.setValue("webSite", webSite);
    requestContext.setValue("website", webSite);

    // Get the current asset and section and store them in the surf request
    // context
    String path = request.getPathInfo();
    PathResolutionDetails resolvedPath = webSite.resolvePath(path);

    if (resolvedPath.isRedirect()) {
        String location = resolvedPath.getRedirectLocation();
        if (location.startsWith("/")) {
            location = contextPath + location;
        }
        response.sendRedirect(location);
        return false;
    }

    requestContext.setValue("asset", resolvedPath.getAsset());
    Section section = resolvedPath.getSection();
    if (section == null) {
        // If we haven't been able to resolve the section then use the root section 
        section = webSite.getRootSection();
    }
    requestContext.setValue("section", section);

    setLocaleFromPath(requestContext, path);

    return super.preHandle(request, response, handler);
}

From source file:org.energy_home.jemma.ah.webui.energyathome.ekitchen.EnergyAtHome.java

private boolean redirectToLoginPage(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String redirect = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + applicationWebAlias + "/conf/login.html";
    response.sendRedirect(redirect);//w ww  .jav  a 2  s. c om
    return true;
}

From source file:org.chtijbug.drools.platform.web.filter.DynamicBaseFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    logger.debug(">> doFilterInternal()");
    try {//w  w  w  .j a  v  a 2s .c  o  m
        PrintWriter out = response.getWriter();
        CharResponseWrapper wrapper = new CharResponseWrapper(response);
        filterChain.doFilter(request, wrapper);

        String baseHref = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/";
        logger.debug("About to replace the base href element with {}", baseHref);
        String modifiedHtml = baseElementPattern.matcher(wrapper.toString())
                .replaceAll("<base href=\"" + baseHref + "\"");
        logger.debug("Modified HTML content : {}", modifiedHtml);
        // Write our modified text to the real response
        response.setContentLength(modifiedHtml.getBytes().length);
        out.write(modifiedHtml);
        out.close();
    } catch (Throwable t) {
        logger.error(t.getMessage());
    } finally {
        logger.debug("<< doFilterInternal()");
    }
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

private URL getURL(HttpServletRequest req, String uriString) throws MalformedURLException {
    String s = uriString.toLowerCase();
    if ((s.startsWith("http://")) || (s.startsWith("https://"))) {
        return new URL(uriString);
    } else if (s.startsWith("/")) {
        return new URL(req.getScheme(), req.getServerName(), req.getServerPort(), uriString);
    } else {//from   w w  w. j a v a  2 s  .c o  m
        return new URL(req.getScheme(), req.getServerName(), req.getServerPort(),
                (req.getContextPath() + "/" + uriString));
    }
}