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:se.vgregion.urlservice.controllers.RedirectController.java

/**
 * Handle redirects//from  w w w. j a v a2 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.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();/*from   ww w  . j ava  2  s . c  o  m*/
    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:co.kuali.coeus.reporting.web.struts.action.ReportForwardAction.java

protected String getClientId(final HttpServletRequest request) {
    String clientId = System.getenv(CLUSTER_ID_VAR);

    if (clientId == null) {
        clientId = request.getServerName();
        LOG.debug("Client ID could not be found in env. vars., using server name: " + clientId);
    } else {/*  www.  j a  v a  2s .  c  om*/
        LOG.debug("Client ID is: " + clientId);
    }

    return clientId;
}

From source file:com.icesoft.faces.renderkit.IncludeRenderer.java

public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
    if (context == null || component == null) {
        throw new NullPointerException("Null Faces context or component parameter");
    }//from   w  ww  .  j a v  a 2  s . c  o  m
    // suppress rendering if "rendered" property on the component is
    // false.
    if (!component.isRendered()) {
        return;
    }

    String page = (String) component.getAttributes().get("page");

    HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
    URI absoluteURI = null;
    try {
        absoluteURI = new URI(request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + request.getRequestURI());
        URL includedURL = absoluteURI.resolve(page).toURL();
        URLConnection includedConnection = includedURL.openConnection();
        includedConnection.setRequestProperty("Cookie",
                "JSESSIONID=" + ((HttpSession) context.getExternalContext().getSession(false)).getId());
        Reader contentsReader = new InputStreamReader(includedConnection.getInputStream());

        try {
            StringWriter includedContents = new StringWriter();
            char[] buf = new char[2000];
            int len = 0;
            while ((len = contentsReader.read(buf)) > -1) {
                includedContents.write(buf, 0, len);
            }

            ((UIOutput) component).setValue(includedContents.toString());
        } finally {
            contentsReader.close();
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
    }

    super.encodeBegin(context, component);
}

From source file:com.redhat.rhn.frontend.servlets.PxtCookieManager.java

/**
 * Determines the pxt cookie name. The name will include the server name from the
 * request if the <code>web.allow_pxt_personalities</code> property in rhn.conf is set.
 *
 * @param request The current request.//from w  ww . ja  v  a  2 s  . c o  m
 *
 * @return The pxt cookie name.
 */
protected String getCookieName(HttpServletRequest request) {
    Config c = Config.get();
    int personality = c.getInt(ConfigDefaults.WEB_ALLOW_PXT_PERSONALITIES);

    if (personality > 0) {
        String[] name = StringUtils.split(request.getServerName(), '.');
        return name[0] + "-" + PXT_SESSION_COOKIE_NAME;
    }

    return PXT_SESSION_COOKIE_NAME;
}

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 w w  w .j  a  v  a2s .  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:com.cpjit.swagger4j.DefaultConfigResolver.java

private Properties loadConfig(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream(configFile);
    props.load(is);// w  w  w.ja  va 2  s . c o  m
    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;
}

From source file:ManageDatasetFiles.java

public String getServerUrl(HttpServletRequest request) {
    String uri = request.getScheme() + "://" + // "http" + "://
            request.getServerName() + // "myhost"
            ":" + // ":"
            request.getServerPort() + // "8080"
            request.getRequestURI();//+       // "/people"

    int lastbackslash = uri.lastIndexOf("/");
    return uri.substring(0, lastbackslash);
}

From source file:com.amediamanager.controller.VideoController.java

@RequestMapping(value = "/video/upload", method = RequestMethod.GET)
public String videoUpload(ModelMap model, HttpServletRequest request, @ModelAttribute User user) {
    // Video redirect URL
    String redirectUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/video/ingest";

    // Prepare S3 form upload
    VideoUploadFormSigner formSigner = new VideoUploadFormSigner(
            config.getProperty(ConfigProps.S3_UPLOAD_BUCKET), config.getProperty(ConfigProps.S3_UPLOAD_PREFIX),
            user, config, redirectUrl);//from  w  w  w  .  j  a  v  a2  s  .  c o  m

    model.addAttribute("formSigner", formSigner);
    model.addAttribute("templateName", "video_upload");

    return "base";
}

From source file:info.magnolia.cms.filters.HostSecurityFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String uri = request.getRequestURI();
    String host = request.getServerName();
    Boolean isHostValid = null;/*  w  w w .jav  a2s  . c o m*/

    for (String[] mapping : uriToHost) {
        if (uri.startsWith(mapping[0])) {
            // set to false only if exist at least one matching pattern
            if (isHostValid == null) {
                isHostValid = false;
            }
            // url allowed on this host
            if (host.endsWith(mapping[1])) {
                isHostValid = true;
                break;
            }

        }
    }
    if (isHostValid != null && !isHostValid.booleanValue()) {
        response.setStatus(404);
        return;
    }

    chain.doFilter(request, response);

}