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.infoglue.cms.util.CmsPropertyHandler.java

public static void registerDefaultSchemeAndPort(HttpServletRequest request) {
    if (defaultScheme == null || defaultPort == null && request != null) {
        defaultScheme = request.getScheme();
        defaultPort = request.getLocalPort();
        logger.info("Registered defaultScheme:" + defaultScheme + " and defaultPort:" + defaultPort);
    }//from w  ww.ja v a 2 s  . com
}

From source file:io.starter.datamodel.Sys.java

/**
 * Get the /1.0/application.wadl/* www  .j a va 2  s  .c  o  m*/
 * 
 * TODO: implement extended WADL Apply XSLT to the WADL output to generate
 * human-readable api docs per: https://wikis.oracle.com/display/Jersey/WADL
 * 
 * 
 * @return
 * @throws IOException
 * @throws TransformerException
 */
@GET
@Path("apidocs")
@Produces(MediaType.TEXT_HTML)
public String getWADL(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse)
        throws IOException, TransformerException {

    servletResponse.addHeader("Access-Control-Allow-Origin", "*");

    // Transform the WADL to HTML using XSLT
    TransformerFactory factory = TransformerFactory.newInstance();

    // Make a URL to the XML
    String iserv = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":"
            + servletRequest.getServerPort() + "/" + SystemConstants.REST_BASE_PATH + "/";
    URL url = new URL(iserv + WADL_SOURCE_URL);

    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    Source text = new StreamSource(con.getInputStream());

    // path to the XSLT
    URL urlx = new URL(SystemConstants.REST_API_SERVER_HOST + "/wadl_html_doc.xslt");
    HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();

    InputStream is = null;

    is = new BufferedInputStream(urlConnection.getInputStream());

    Source xslt = new StreamSource(is);

    Transformer transformer = factory.newTransformer(xslt);
    servletResponse.setContentType("text/html");
    OutputStream ous = servletResponse.getOutputStream();

    transformer.transform(text, new StreamResult(ous));
    ous.flush();
    ous.close();

    return "ok";
}

From source file:org.daxplore.presenter.server.servlets.PresenterServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    PersistenceManager pm = null;//from  w  w  w.  ja  va  2 s  . c o m
    try {
        // Get input from URL
        //TODO use better and more stable parsing
        String prefix = request.getPathInfo();
        if (prefix != null && !prefix.isEmpty()) {
            if (prefix.charAt(0) == '/') {
                prefix = prefix.substring(1);
            }
            if (!prefix.isEmpty() && prefix.charAt(prefix.length() - 1) == '/') {
                prefix = prefix.substring(0, prefix.length() - 2);
            }
        }
        String useragent = request.getHeader("user-agent");
        Cookie[] cookies = request.getCookies();
        String feature = request.getParameter("f");
        String baseurl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

        // Clean user input
        if (prefix == null || !SharedResourceTools.isSyntacticallyValidPrefix(prefix)) {
            throw new BadRequestException(
                    "Someone tried to access a syntactically invalid prefix: '" + prefix + "'");
        }

        boolean browserSupported = true;
        double ieversion = ServerTools.getInternetExplorerVersion(useragent);
        if (useragent == null | (ieversion > 0.0 & ieversion < 8.0)) {
            browserSupported = false;
        }

        boolean ignoreBadBrowser = false;
        if (cookies != null) {
            ignoreBadBrowser = ServerTools.ignoreBadBrowser(cookies);
        }
        browserSupported |= ignoreBadBrowser;

        pm = PMF.get().getPersistenceManager();
        String googleAnalyticsID = SettingItemStore.getProperty(pm, prefix, "adminpanel", "gaID");
        String gaTemplate = "";
        if (googleAnalyticsID != null && !googleAnalyticsID.equals("")) {
            if (googleAnalyticsTrackingTemplate == null) {
                try {
                    googleAnalyticsTrackingTemplate = IOUtils
                            .toString(getServletContext().getResourceAsStream("/js/ga-tracking.js"));
                } catch (IOException e) {
                    throw new InternalServerException("Failed to load the google analytics tracking template",
                            e);
                }
            }
            gaTemplate = MessageFormat.format(googleAnalyticsTrackingTemplate, googleAnalyticsID);
        }

        String responseHTML = "";
        if (!browserSupported) {
            responseHTML = getUnsupportedBrowserHTML(baseurl, gaTemplate);
        } else {
            Locale locale = ServerTools.selectLocale(request, prefix);

            String secondaryFlagText = SettingItemStore.getLocalizedProperty(pm, prefix, "properties/usertexts",
                    locale, "secondary_flag");
            //TODO handle timepoints properly
            String timepoint0Text = SettingItemStore.getLocalizedProperty(pm, prefix, "properties/usertexts",
                    locale, "timepoint_0");
            String timepoint1Text = SettingItemStore.getLocalizedProperty(pm, prefix, "properties/usertexts",
                    locale, "timepoint_1");
            String pageTitle = SettingItemStore.getLocalizedProperty(pm, prefix, "properties/usertexts", locale,
                    "page_title");
            ServerPrefixProperties prefixProperties = new ServerPrefixProperties(prefix, secondaryFlagText,
                    timepoint0Text, timepoint1Text, pageTitle);

            if (feature != null && feature.equalsIgnoreCase("embed")) { // embedded chart

                // TODO clean query string
                String queryString = request.getParameter("q");
                responseHTML = getEmbedHTML(pm, prefix, locale, queryString, baseurl, prefixProperties,
                        gaTemplate);

            } else if (feature != null && feature.equalsIgnoreCase("print")) { // printer-friendly chart

                String serverPath = request.getRequestURL().toString();
                // remove last slash
                if (serverPath.charAt(serverPath.length() - 1) == '/') {
                    serverPath = serverPath.substring(0, serverPath.length() - 1);
                }
                // remove module name
                serverPath = serverPath.substring(0, serverPath.lastIndexOf("/"));

                // TODO clean query string
                String queryString = request.getParameter("q");
                responseHTML = getPrintHTML(pm, prefix, locale, serverPath, queryString, baseurl, gaTemplate);

            } else { // standard presenter

                responseHTML = getPresenterHTML(pm, prefix, locale, baseurl, prefixProperties, gaTemplate);

            }
        }

        response.setContentType("text/html; charset=UTF-8");
        try (Writer writer = response.getWriter()) {
            writer.write(responseHTML);
        } catch (IOException e) {
            throw new InternalServerException("Failed to display presenter servlet", e);
        }
    } catch (BadRequestException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (InternalServerException e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (RuntimeException e) {
        logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        if (pm != null) {
            pm.close();
        }
    }
}

From source file:org.apache.axis2.transport.http.AxisServlet.java

/**
 * Preprocess the request. This will:/*  w w  w  . jav  a 2s.  c  o  m*/
 * <ul>
 * <li>Set the context root if it is not set already (by calling
 * {@link #initContextRoot(HttpServletRequest)}).
 * <li>Remember the port number if port autodetection is enabled.
 * <li>Reject the request if no {@link AxisServletListener} has been registered for the
 * protocol.
 * </ul>
 * 
 * @param req the request to preprocess
 */
// This method should not be part of the public API. In particular we must not allow subclasses
// to override this method because we don't make any guarantees as to when exactly this method
// is called.
private void preprocessRequest(HttpServletRequest req) throws ServletException {
    initContextRoot(req);

    TransportInDescription transportInDescription = req.isSecure()
            ? this.axisConfiguration.getTransportIn(Constants.TRANSPORT_HTTPS)
            : this.axisConfiguration.getTransportIn(Constants.TRANSPORT_HTTP);

    if (transportInDescription == null) {
        throw new ServletException(req.getScheme() + " is forbidden");
    } else {
        if (transportInDescription.getReceiver() instanceof AxisServletListener) {
            AxisServletListener listner = (AxisServletListener) transportInDescription.getReceiver();
            // Autodetect the port number if necessary
            if (listner.getPort() == -1) {
                listner.setPort(req.getServerPort());
            }
        }
    }

}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * If the request has a valid authentication token it allows the request to continue to
 * the target resource,//from   w  w w. j av a  2  s .  c  o  m
 * otherwise it triggers a GSS-API sequence for authentication
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got token {} from httpRequest {}", token, getRequestURL(httpRequest));
                if (null != token) {
                    LOG.debug("token.isExpired() = " + token.isExpired());
                }
            }
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            if (!ex.getMessage().equals("Empty token")) {
                // will be sent back in a 401 unless filter authenticates
                authenticationEx = ex;
            }
            token = null;
        }
        if (managementOperation(token, httpRequest, httpResponse)) {
            if (token == null || token.isExpired()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication. handler: {}", getRequestURL(httpRequest),
                            this.getClass());
                }
                token = authenticate(httpRequest, httpResponse);
                if (token != null && token != AuthenticationToken.ANONYMOUS) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            if (token.getMaxInactives() > 0) {
                    //              token.setMaxInactives(System.currentTimeMillis()
                    //                  + getTokenMaxInactiveInterval() * 1000);
                    //            }
                    if (token.getExpires() != 0) {
                        token.setExpires(System.currentTimeMillis() + getTokenValidity() * 1000);
                    }
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };

                // If cookie persistence is configured to false,
                // it means the cookie will be a session cookie.
                // If the token is an old one, renew the its tokenMaxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getTokenMaxInactiveInterval() > 0) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            token.setMaxInactives(System.currentTimeMillis()
                    //                + getTokenMaxInactiveInterval() * 1000);
                    token.setExpires(token.getExpires());
                    newToken = true;
                }
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isCookiePersistent(), isHttps);
                }
                KerberosToken kerberosToken = new KerberosToken(token.getUserName(), token.toString());
                SecurityUtils.getSubject().login(kerberosToken);
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("managementOperation returned false for request {}." + " token: {}",
                        getRequestURL(httpRequest), token);
            }
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(),
                    isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                httpResponse.sendError(errCode, "Authentication required");
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:com.sun.socialsite.business.DefaultURLStrategy.java

/**
 * Get the appropriate Gadget Server URL for the specified request.
 * The returned URL will not end with a trailing slash.  If the
 * "socialsite.gadgets.server.url" property is populated and contains
 * any wildcards ("*"), they will be replaced with the specified
 * replacementValue./*w  w  w .j av  a2  s . c om*/
 */
public String getGadgetServerURL(HttpServletRequest request, String replacementValue) {

    StringBuilder sb = new StringBuilder();

    try {

        String propVal = Config.getProperty("socialsite.gadgets.server.url");
        if (propVal != null) {
            String actualValue = propVal.replace("*", replacementValue);
            sb.append(actualValue);
        } else {
            if (Config.getBooleanProperty("socialsite.gadgets.use-cookie-jail")) {
                // For now, we'll use an IP-based URL to provide a cookie jail
                InetAddress addr = InetAddress.getByName(request.getServerName());
                if (addr instanceof Inet6Address) {
                    sb.append(request.getScheme()).append("://[").append(addr.getHostAddress()).append("]");
                } else {
                    sb.append(request.getScheme()).append("://").append(addr.getHostAddress());
                }
            } else {
                sb.append(request.getScheme()).append("://").append(request.getServerName());
            }
            switch (request.getServerPort()) {
            case 80:
                if (!(request.getScheme().equalsIgnoreCase("http"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            case 443:
                if (!(request.getScheme().equalsIgnoreCase("https"))) {
                    sb.append(":").append(request.getServerPort());
                }
                break;
            default:
                sb.append(":").append(request.getServerPort());
            }
            sb.append(request.getContextPath());
            sb.append("/gadgets");
        }

    } catch (Exception e) {
        log.warn(e);
    }

    // We don't want our result to end with a slash
    while (sb.charAt(sb.length() - 1) == '/') {
        sb.deleteCharAt(sb.length() - 1);
    }

    return sb.toString();

}

From source file:io.getlime.push.controller.web.WebAdminController.java

@RequestMapping(value = "web/admin/message/create/do.submit", method = RequestMethod.POST)
public String actionCreatePushMessage(@Valid ComposePushMessageForm form, BindingResult bindingResult,
        RedirectAttributes attr, HttpServletRequest httpRequest) {
    if (bindingResult.hasErrors()) {
        attr.addFlashAttribute("fields", bindingResult);
        attr.addFlashAttribute("form", form);
        return "redirect:/web/admin/message/create";
    }//  w  w w .  ja v  a 2 s  . c  o m
    SendPushMessageRequest request = new SendPushMessageRequest();
    request.setAppId(form.getAppId());
    PushMessage message = new PushMessage();
    message.setUserId(form.getUserId());
    PushMessageBody body = new PushMessageBody();
    body.setTitle(form.getTitle());
    body.setBody(form.getBody());
    body.setSound(form.isSound() ? "default" : null);
    message.setBody(body);
    request.setMessage(message);
    HttpEntity<ObjectRequest<SendPushMessageRequest>> requestEntity = new HttpEntity<>(
            new ObjectRequest<>(request));
    RestTemplate template = new RestTemplate();
    String baseUrl = String.format("%s://%s:%d/%s", httpRequest.getScheme(), httpRequest.getServerName(),
            httpRequest.getServerPort(), httpRequest.getContextPath());
    template.exchange(baseUrl + "/push/message/send", HttpMethod.POST, requestEntity,
            new ParameterizedTypeReference<ObjectResponse<PushMessageSendResult>>() {
            });
    return "redirect:/web/admin/message/create";
}

From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java

/**
 * Determines if the current request matches the <code>SavedRequest</code>. All URL arguments are
 * considered, but <em>not</em> method (POST/GET), cookies, locales, headers or parameters.
 *
 * @param request DOCUMENT ME!//from w  w w  . jav  a2  s  .co  m
 * @param portResolver DOCUMENT ME!
 * @return DOCUMENT ME!
 */
public boolean doesRequestMatch(HttpServletRequest request, PortResolver portResolver) {
    Assert.notNull(request, "Request required");
    Assert.notNull(portResolver, "PortResolver required");

    if (!propertyEquals("pathInfo", this.pathInfo, request.getPathInfo())) {
        return false;
    }

    if (!propertyEquals("queryString", this.queryString, request.getQueryString())) {
        return false;
    }

    if (!propertyEquals("requestURI", this.requestURI, request.getRequestURI())) {
        return false;
    }

    if (!propertyEquals("serverPort", new Integer(this.serverPort),
            new Integer(portResolver.getServerPort(request)))) {
        return false;
    }

    if (!propertyEquals("requestURL", this.requestURL, request.getRequestURL().toString())) {
        return false;
    }

    if (!propertyEquals("scheme", this.scheme, request.getScheme())) {
        return false;
    }

    if (!propertyEquals("serverName", this.serverName, request.getServerName())) {
        return false;
    }

    if (!propertyEquals("contextPath", this.contextPath, request.getContextPath())) {
        return false;
    }

    if (!propertyEquals("servletPath", this.servletPath, request.getServletPath())) {
        return false;
    }

    return true;
}

From source file:org.cyk.ui.web.api.WebNavigationManager.java

public String getRequestUrl(HttpServletRequest request) {
    String url, path = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    if (path == null) {
        url = request.getRequestURL().toString();
        if (StringUtils.isNotEmpty(request.getQueryString()))
            url += Constant.CHARACTER_QUESTION_MARK + request.getQueryString();
    } else {//from  w w w.j a  va 2s .co m
        url = request.getScheme() + Constant.CHARACTER_COLON + Constant.CHARACTER_SLASH
                + Constant.CHARACTER_SLASH + request.getServerName() + Constant.CHARACTER_COLON
                + request.getServerPort() + path;
    }

    //if(StringUtils.isNotEmpty(PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString()))
    //   url += NavigationHelper.QUERY_START+PrettyContext.getCurrentInstance().getRequestQueryString().toQueryString();
    return url;
}