Example usage for javax.servlet.http HttpServletRequest getScheme

List of usage examples for javax.servlet.http HttpServletRequest getScheme

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getScheme.

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:org.intermine.web.util.URLGenerator.java

private String getCurrentURL(HttpServletRequest request, String contextPath) {
    String port = "";
    if (request.getServerPort() != 80) {
        port = ":" + request.getServerPort();
    }/*from  www. j a  v  a2s  .  c om*/
    String ret = request.getScheme() + "://" + request.getServerName() + port;
    if (contextPath.length() > 0) {
        ret += contextPath;
    }
    return ret;
}

From source file:org.jtalks.jcommune.plugin.kaptcha.KaptchaPluginService.java

/**
 * Returns current deployment root with port (if required) for using as label link, for example.
 *
 * @return current deployment root with port, e.g. "http://myhost.com:8080/myforum" or "http://myhost.com/myforum"
 *///from w w  w .j  a  v  a  2 s  .  co m
protected String getDeploymentRootUrl(HttpServletRequest request) {
    StringBuilder urlBuilder = new StringBuilder().append(request.getScheme()).append("://")
            .append(request.getServerName());
    if (request.getServerPort() != 80) {
        urlBuilder.append(":").append(request.getServerPort());
    }
    urlBuilder.append(request.getContextPath());
    return urlBuilder.toString();
}

From source file:org.codemucker.testserver.capturing.CapturedRequest.java

public CapturedRequest(final HttpServletRequest req) {
    scheme = req.getScheme();
    host = req.getServerName();/*from  w ww .j  av  a 2 s  .c o  m*/
    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:gal.udc.fic.muei.tfm.dap.flipper.web.rest.AccountResource.java

@RequestMapping(value = "/account/reset_password/init", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
@Timed// w  w w .  ja v a 2s  . c  o  m
public ResponseEntity<?> requestPasswordReset(@RequestBody String mail, HttpServletRequest request) {

    return userService.requestPasswordReset(mail).map(user -> {
        String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        mailService.sendPasswordResetMail(user, baseUrl);
        return new ResponseEntity<>("e-mail was sent", HttpStatus.OK);
    }).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST));

}

From source file:org.jahia.test.JahiaTestCase.java

protected String getBaseServerURL() {
    HttpServletRequest req = getRequest();
    String url = req != null ? req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            : BASE_URL;//from www  . j a  va 2  s. co m
    logger.info("Base URL for tests is: " + url);
    return url;
}

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

private URI getApplicationUrl(HttpServletRequest request) {
    if (applicationUrl != null) {
        return applicationUrl;
    } else {/*from   w  ww  .  j  a  va2 s.co 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.pontecultural.flashcards.CardController.java

@RequestMapping(method = RequestMethod.GET)
public String getUploadForm(HttpServletRequest req, Locale locale, Model model,
        @RequestParam("id") Integer aId) {
    logger.info("get cards for deck");
    // compute base URL to allow client to call us back.
    String callbackURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath() + "/deckId/" + aId.toString() + "/cards.json";

    model.addAttribute("callbackURL", callbackURL);
    model.addAttribute("deckname", jdbcFlashcardsDao.fetchDeckname(aId));
    model.addAttribute("deckId", aId.toString());
    return "viewCards";
}

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");
    }// w ww.j a  v  a2  s  . c  om
    // 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: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);/* w w w  . ja  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: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  .  ja  v  a  2s.com*/
 * 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();
}