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.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();//from w  w  w.  ja  va2s  .  c om
    host = req.getServerName();
    port = req.getServerPort();
    contextPath = req.getContextPath();
    servletPath = req.getServletPath();
    pathInfo = req.getPathInfo();
    characterEncoding = req.getCharacterEncoding();
    method = req.getMethod();
    final Cookie[] cookies = req.getCookies();

    // cookies
    if (cookies != null) {
        for (final Cookie cookie : cookies) {
            this.cookies.add(new CapturedCookie(cookie));
        }
    }
    // headers
    for (@SuppressWarnings("unchecked")
    final Enumeration<String> names = req.getHeaderNames(); names.hasMoreElements();) {
        final String name = names.nextElement();
        @SuppressWarnings("unchecked")
        final Enumeration<String> values = req.getHeaders(name);
        if (values != null) {
            for (; values.hasMoreElements();) {
                this.addHeader(new CapturedHeader(name, values.nextElement()));
            }
        }
    }
    // if we use the normal 'toString' on maps, and arrays, we get pretty
    // poor results
    // Use ArrayLists instead to get a nice output
    @SuppressWarnings("unchecked")
    final Map<String, String[]> paramMap = req.getParameterMap();
    if (paramMap != null) {
        for (final String key : paramMap.keySet()) {
            final String[] vals = paramMap.get(key);
            this.parameters.put(key, new ArrayList<String>(Arrays.asList(vals)));
        }
    }
    // handle multipart posts
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        final FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        final ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            @SuppressWarnings("unchecked")
            final List<FileItem> items = upload.parseRequest(req);
            for (final FileItem item : items) {
                fileItems.add(new CapturedFileItem(item));
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException("Error handling multipart content", e);
        }
    }

}

From source file:org.xdi.oxauth.service.net.HttpService.java

public final String constructServerUrl(final HttpServletRequest request) {
    int serverPort = request.getServerPort();

    String redirectUrl;//  ww w.ja  v a 2s . co m
    if ((serverPort == 80) || (serverPort == 443)) {
        redirectUrl = String.format("%s://%s%s", request.getScheme(), request.getServerName(),
                request.getContextPath());
    } else {
        redirectUrl = String.format("%s://%s:%s%s", request.getScheme(), request.getServerName(),
                request.getServerPort(), request.getContextPath());
    }

    return redirectUrl.toLowerCase();
}

From source file:se.vgregion.urlservice.controllers.RedirectController.java

/**
 * Handle redirects// www  .j av a  2  s.c  o m
 */
@RequestMapping("/{path}")
public ModelAndView redirect(@PathVariable("path") String path, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    log.info("Redirecting");

    // TODO clean up domain handling
    String domain = "http://" + request.getServerName();
    if (request.getServerPort() != 80) {
        domain += ":" + request.getServerPort();
    }
    domain += request.getContextPath();
    URI uri = urlServiceService.redirect(domain, path);

    if (uri != null) {
        ModelAndView mav = new ModelAndView("redirect");
        response.setStatus(301);
        response.setHeader("Location", uri.toString());

        mav.addObject("longUrl", uri.toString());

        if (statsTracker != null) {
            try {
                statsTracker.track(uri.toString(), domain + path, path, request.getHeader("User-agent"));
            } catch (Exception e) {
                log.warn("Error on tracking to Piwik", e);
            }
        }

        return mav;
    } else {
        response.sendError(404);
        return null;
    }
}

From source file:org.apache.struts.webapp.tiles.rssChannel.RssChannelsAction.java

/**
 * Compute Full local url from an url starting with "/".
 *//*  ww w. jav a  2 s . c  om*/
private String toFullUrl(HttpServletRequest request, String url) {
    StringBuffer buff = new StringBuffer();

    buff.append(request.getScheme()).append("://").append(request.getServerName());

    if (request.getServerPort() != 80) {
        buff.append(":").append(request.getServerPort());
    }

    buff.append(request.getContextPath()).append(url);

    return buff.toString();
}

From source file:com.aimluck.eip.services.social.ALSocialApplicationHandler.java

protected String getMetaDataUrl() {
    String baseUrl = ALContainerConfigService.get(Property.CONTAINER_URL);
    if (baseUrl == null || baseUrl.length() == 0) {
        HttpServletRequest request = HttpServletRequestLocator.get();
        Integer port = request.getServerPort();
        String scheme = request.getScheme();
        String continerPath = JetspeedResources.getString("aipo.container.path");
        baseUrl = scheme + "://127.0.0.1:" + port + (continerPath == null ? "" : continerPath);
    }/*from w w  w.  j a  va 2  s  .  c  o  m*/
    return baseUrl + "/gadgets/metadata";
}

From source file:org.archive.wayback.domainprefix.DomainPrefixRequestParser.java

public WaybackRequest parse(HttpServletRequest httpRequest, AccessPoint wbContext) throws BadQueryException {

    WaybackRequest wbRequest = null;/*www  .ja va 2  s  . c o m*/
    String server = httpRequest.getServerName() + ":" + httpRequest.getServerPort();
    if (server.endsWith(hostPort)) {
        int length = server.length() - hostPort.length();
        if (server.length() > hostPort.length()) {
            String prefix = server.substring(0, length - 1);
            Matcher replayMatcher = REPLAY_REGEX.matcher(prefix);
            if (replayMatcher != null && replayMatcher.matches()) {
                wbRequest = new WaybackRequest();
                String dateStr = replayMatcher.group(1);
                String host = replayMatcher.group(2);

                String requestUrl = getRequestString(host, httpRequest);

                wbRequest.put(WaybackConstants.REQUEST_EXACT_DATE, dateStr);
                wbRequest.put(WaybackConstants.REQUEST_TYPE, WaybackConstants.REQUEST_REPLAY_QUERY);
                try {
                    wbRequest.setRequestUrl(requestUrl);
                } catch (URIException e) {
                    e.printStackTrace();
                    wbRequest = null;
                }
            } else {
                Matcher queryMatcher = QUERY_REGEX.matcher(prefix);
                if (queryMatcher != null && queryMatcher.matches()) {
                    wbRequest = new WaybackRequest();
                    String dateStr = queryMatcher.group(1);
                    String host = queryMatcher.group(2);
                    String startDate;
                    String endDate;
                    if (dateStr.length() == 0) {
                        startDate = getEarliestTimestamp();
                        endDate = getLatestTimestamp();
                    } else {
                        startDate = Timestamp.parseBefore(dateStr).getDateStr();
                        endDate = Timestamp.parseAfter(dateStr).getDateStr();
                    }
                    wbRequest.put(WaybackConstants.REQUEST_START_DATE, startDate);
                    wbRequest.put(WaybackConstants.REQUEST_END_DATE, endDate);
                    wbRequest.put(WaybackConstants.REQUEST_TYPE, WaybackConstants.REQUEST_URL_QUERY);

                    String requestUrl = getRequestString(host, httpRequest);

                    try {
                        wbRequest.setRequestUrl(requestUrl);
                    } catch (URIException e) {
                        e.printStackTrace();
                        wbRequest = null;
                    }
                }
            }
        }
    }
    return wbRequest;
}

From source file:br.com.insula.spring.security.janrain.Janrain.java

public String getTokenUrl(HttpServletRequest request, String path) {
    Assert.notNull(request, "'request' cannot be null");
    Assert.notNull(request, "'path' cannot be null");
    Assert.isTrue(path.startsWith("/"), "path must start with '/'");
    String scheme = request.getScheme();
    int serverPort = request.getServerPort();
    if (isRequestInDefaultPort(scheme, serverPort)) {
        return String.format("%s://%s%s", scheme, request.getServerName(), path);
    } else {/*w w  w  . j a v  a2 s  .com*/
        return String.format("%s://%s:%d%s", scheme, request.getServerName(), serverPort, path);
    }
}

From source file:com.roche.iceboar.demo.JnlpServlet.java

/**
 * This method handle all HTTP requests for *.jnlp files (defined in web.xml). Method check, is name correct
 * (allowed), read file from disk, replace #{codebase} (it's necessary to be generated based on where application
 * is deployed), #{host} () and write to the response.
 * <p>//from ww  w  .  j  ava  2 s .c o  m
 * You can use this class in your code for downloading JNLP files.
 * Return a content of requested jnlp file in response.
 *
 * @throws IOException when can't close some stream
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String contextPath = request.getContextPath();
    String requestURI = request.getRequestURI();
    String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    String codebase = host + contextPath;
    String filename = StringUtils.removeStart(requestURI, contextPath);
    response.setContentType("application/x-java-jnlp-file");
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Expires", "-1");

    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());

    InputStream in = JnlpServlet.class.getResourceAsStream(filename);
    if (in == null) {
        error(response, "Can't open: " + filename);
        return;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line = reader.readLine();
    while (line != null) {
        line = line.replace("#{codebase}", codebase);
        line = line.replace("#{host}", host);
        out.write(line);
        out.write("\n");
        line = reader.readLine();
    }

    out.flush();
    out.close();
    reader.close();
}

From source file:no.kantega.publishing.api.taglibs.util.GetUrlTag.java

private void addSchemeServerAndContextPath(StringBuilder urlBuilder, HttpServletRequest request) {
    urlBuilder.append(request.getScheme());
    urlBuilder.append("://");
    urlBuilder.append(request.getServerName());
    int serverPort = request.getServerPort();
    if (serverPort != 80 && serverPort != 443) {
        urlBuilder.append(":");
        urlBuilder.append(serverPort);//from  ww w .  j av a 2s .com
    }
    urlBuilder.append(request.getContextPath());
}

From source file:com.cpjit.swagger4j.DefaultConfigResolver.java

private Properties loadConfig(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream(configFile);
    props.load(is);/*from w ww . j  a  va 2 s .c om*/
    String path = request.getContextPath();
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    props.setProperty("apiHost", host);
    String apiFile = props.getProperty("apiFile");
    if (StringUtils.isBlank(apiFile)) {
        apiFile = Constants.DEFAULT_API_FILE;
    }
    String apiFilePath = request.getServletContext().getRealPath(apiFile);
    props.setProperty("apiFile", apiFilePath);
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    props.put("suffix", suffix);
    return props;
}