Example usage for javax.servlet.http HttpServletRequest isSecure

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

Introduction

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

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testPassiveLoginPkiPost()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException {
    String samlRequest = authNRequestPassivePkiPost;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert/*w  w  w.  j  a  va  2  s  .  c  o  m*/
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request);

    assertThat(response.getEntity().toString(), containsString("Form Submit"));
    assertThat(response.getEntity().toString(), containsString("SAMLResponse"));
    assertThat(response.getEntity().toString(), containsString("RelayState"));
}

From source file:ru.org.linux.tag.TagPageController.java

private Map<String, Object> getNewsSection(HttpServletRequest request, String tag) throws TagNotFoundException {
    Template tmpl = Template.getTemplate(request);

    Section newsSection = sectionService.getSection(Section.SECTION_NEWS);

    List<Topic> newsTopics = topicListService.getTopicsFeed(newsSection, null, tag, 0, null, null,
            TOTAL_NEWS_COUNT);//from  ww  w  .j  a v  a  2 s.  c om

    List<Topic> fullNewsTopics = headOrEmpty(newsTopics);
    List<Topic> briefNewsTopics = tailOrEmpty(newsTopics);

    List<PersonalizedPreparedTopic> fullNews = prepareService.prepareMessagesForUser(fullNewsTopics,
            request.isSecure(), tmpl.getCurrentUser(), tmpl.getProf(), false);

    ImmutableListMultimap<String, Topic> briefNews = datePartition(briefNewsTopics, COMMITDATE_EXTRACTOR);

    ImmutableMap.Builder<String, Object> out = ImmutableMap.builder();

    out.put("addNews", AddTopicController.getAddUrl(newsSection, tag));

    if (newsTopics.size() == TOTAL_NEWS_COUNT) {
        out.put("moreNews", TagTopicListController.tagListUrl(tag, newsSection));
    }

    out.put("fullNews", fullNews);
    out.put("briefNews", split(briefNews));

    return out.build();
}

From source file:org.springframework.security.saml.context.SAMLContextProviderImpl.java

protected void populateGenericContext(HttpServletRequest request, HttpServletResponse response,
        SAMLMessageContext context) throws MetadataProviderException {

    HttpServletRequestAdapter inTransport = new HttpServletRequestAdapter(request);
    HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, request.isSecure());

    // Store attribute which cannot be located from InTransport directly
    request.setAttribute(org.springframework.security.saml.SAMLConstants.LOCAL_CONTEXT_PATH,
            request.getContextPath());//  w ww .  ja  v  a 2  s.com

    context.setMetadataProvider(metadata);
    context.setInboundMessageTransport(inTransport);
    context.setOutboundMessageTransport(outTransport);

    context.setMessageStorage(storageFactory.getMessageStorage(request));

}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException      Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *///from  w w  w . j a  va  2 s. com
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:org.dspace.app.util.SyndicationFeed.java

private String resolveURL(HttpServletRequest request, DSpaceObject dso) {
    // If no object given then just link to the whole repository,
    // since no offical handle exists so we have to use local resolution.
    if (dso == null) {
        if (baseURL == null) {
            if (request == null) {
                baseURL = ConfigurationManager.getProperty("dspace.url");
            } else {
                baseURL = (request.isSecure()) ? "https://" : "http://";
                baseURL += ConfigurationManager.getProperty("dspace.hostname");
                baseURL += ":" + request.getServerPort();
                baseURL += request.getContextPath();
            }/*from w  w  w. ja va 2 s .co  m*/
        }
        return baseURL;
    }

    // return a link to handle in repository
    else if (ConfigurationManager.getBooleanProperty("webui.feed.localresolve")) {
        return resolveURL(request, null) + "/handle/" + dso.getHandle();
    }

    // link to the Handle server or other persistent URL source
    else {
        return HandleManager.getCanonicalForm(dso.getHandle());
    }
}

From source file:com.adito.boot.Util.java

/**
 * Dump all request parameters and some other useful stuff from
 * the request to {@link System#err}/*ww  w . j  a v  a  2 s  . com*/
 * 
 * @param request request to get parameters from
 */
public static void dumpRequest(HttpServletRequest request) {
    System.err.println("Context Path " + request.getContextPath());
    System.err.println("Path Translated " + request.getPathTranslated());
    System.err.println("Path Info " + request.getPathInfo());
    System.err.println("Query: " + request.getQueryString());
    System.err.println("Request URI: " + request.getRequestURI());
    System.err.println("Request URL: " + request.getRequestURL());
    System.err.println("Is Secure: " + request.isSecure());
    System.err.println("Scheme: " + request.getScheme());
    dumpRequestParameters(request);
    dumpRequestAttributes(request);
    dumpRequestHeaders(request);

}

From source file:com.almende.eve.transport.http.DebugServlet.java

/**
 * Handle session./*w w w  .  java 2s  . co  m*/
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleSession(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    try {

        if (req.getSession(false) != null) {
            return true;
        }
        // TODO: make sure connection is secure if configured to enforce
        // that.
        final Handshake hs = doHandShake(req);
        if (hs.equals(Handshake.INVALID)) {
            return false;
        }

        final boolean doAuthentication = HttpService.doAuthentication(myUrl);
        if (hs.equals(Handshake.NAK) && doAuthentication) {
            if (!req.isSecure()) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Request needs to be secured with SSL for session management!");
                return false;
            }
            if (!req.authenticate(res)) {
                return false;
            }
        }
        // generate new session:
        req.getSession(true);
    } catch (final Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Exception running HandleSession:" + e.getMessage());
        LOG.log(Level.WARNING, "", e);
        return false;
    }
    return true;
}

From source file:ru.org.linux.topic.TopicController.java

private ModelAndView getMessageNew(Section section, WebRequest webRequest, HttpServletRequest request,
        HttpServletResponse response, int page, String filter, String groupName, int msgid) throws Exception {
    Topic topic = messageDao.getById(msgid);
    Template tmpl = Template.getTemplate(request);

    PreparedTopic preparedMessage = messagePrepareService.prepareTopic(topic, request.isSecure(),
            tmpl.getCurrentUser());//from  w ww .j  a v  a  2 s.  c om
    Group group = preparedMessage.getGroup();

    if (!group.getUrlName().equals(groupName) || group.getSectionId() != section.getId()) {
        return new ModelAndView(new RedirectView(topic.getLink()));
    }

    Map<String, Object> params = new HashMap<>();

    boolean showDeleted = request.getParameter("deleted") != null;
    if (showDeleted) {
        page = -1;
    }

    boolean rss = request.getParameter("output") != null && "rss".equals(request.getParameter("output"));

    if (rss && topic.isExpired()) {
        throw new MessageNotFoundException(topic.getId(), "no more comments");
    }

    if (!tmpl.isModeratorSession()) {
        if (showDeleted && !"POST".equals(request.getMethod())) {
            return new ModelAndView(new RedirectView(topic.getLink()));
        }
    }

    if (page == -1 && !tmpl.isSessionAuthorized()) {
        return new ModelAndView(new RedirectView(topic.getLink()));
    }

    int pages = topic.getPageCount(tmpl.getProf().getMessages());

    if (page >= pages && (page > 0 || pages > 0)) {
        if (pages == 0) {
            return new ModelAndView(new RedirectView(topic.getLink()));
        } else {
            return new ModelAndView(new RedirectView(topic.getLinkPage(pages - 1)));
        }
    }

    if (showDeleted) {
        if (!tmpl.isSessionAuthorized()) {
            throw new BadInputException("    ??");
        }
    }

    params.put("showDeleted", showDeleted);

    User currentUser = AuthUtil.getCurrentUser();

    if (topic.isExpired() && showDeleted && !tmpl.isModeratorSession()) {
        throw new MessageNotFoundException(topic.getId(),
                "? ?    ? ");
    }

    permissionService.checkView(topic, currentUser);

    if (group.getCommentsRestriction() == -1 && !tmpl.isSessionAuthorized()) {
        throw new AccessViolationException(" ? ? ?");
    }

    params.put("message", topic);
    params.put("preparedMessage", preparedMessage);

    if (topic.isExpired()) {
        response.setDateHeader("Expires", System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L);
    }

    CommentList comments = commentService.getCommentList(topic, showDeleted);

    if (!rss) {
        params.put("page", page);
        params.put("group", group);
        params.put("showAdsense", !tmpl.isSessionAuthorized() || !tmpl.getProf().isHideAdsense());

        if (!tmpl.isSessionAuthorized()) { // because users have IgnoreList and memories
            String etag = getEtag(topic, tmpl);
            response.setHeader("Etag", etag);

            if (request.getHeader("If-None-Match") != null) {
                if (etag.equals(request.getHeader("If-None-Match"))) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }
            } else if (checkLastModified(webRequest, topic)) {
                return null;
            }
        }

        params.put("messageMenu", messagePrepareService.getTopicMenu(preparedMessage, currentUser,
                request.isSecure(), tmpl.getProf(), true));

        Set<Integer> ignoreList;

        if (currentUser != null) {
            ignoreList = ignoreListDao.get(currentUser);
        } else {
            ignoreList = ImmutableSet.of();
        }

        int defaultFilterMode = getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty());
        int filterMode;

        if (filter != null) {
            filterMode = CommentFilter.parseFilterChain(filter);

            if (!ignoreList.isEmpty() && filterMode == CommentFilter.FILTER_ANONYMOUS) {
                filterMode += CommentFilter.FILTER_IGNORED;
            }
        } else {
            filterMode = defaultFilterMode;
        }

        params.put("filterMode", CommentFilter.toString(filterMode));
        params.put("defaultFilterMode", CommentFilter.toString(defaultFilterMode));

        loadTopicScroller(params, topic, currentUser, !ignoreList.isEmpty());

        Set<Integer> hideSet = commentService.makeHideSet(comments, filterMode, ignoreList);

        CommentFilter cv = new CommentFilter(comments);

        boolean reverse = tmpl.getProf().isShowNewFirst();

        List<Comment> commentsFiltred = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(),
                hideSet);
        List<Comment> commentsFull = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(),
                ImmutableSet.<Integer>of());

        params.put("unfilteredCount", commentsFull.size());

        List<PreparedComment> commentsPrepared = prepareService.prepareCommentList(comments, commentsFiltred,
                request.isSecure(), tmpl, topic);

        params.put("commentsPrepared", commentsPrepared);

        IPBlockInfo ipBlockInfo = ipBlockDao.getBlockInfo(request.getRemoteAddr());
        params.put("ipBlockInfo", ipBlockInfo);

        if (pages > 1 && !showDeleted) {
            params.put("pages",
                    buildPages(topic, tmpl.getProf().getMessages(), filterMode, defaultFilterMode, page));
        }
    } else {
        CommentFilter cv = new CommentFilter(comments);

        List<Comment> commentsFiltred = cv.getCommentsForPage(true, 0, RSS_DEFAULT, ImmutableSet.<Integer>of());

        List<PreparedRSSComment> commentsPrepared = prepareService.prepareCommentListRSS(commentsFiltred,
                request.isSecure());

        params.put("commentsPrepared", commentsPrepared);
        LorURL lorURL = new LorURL(configuration.getMainURI(), configuration.getMainUrl());
        params.put("mainURL", lorURL.fixScheme(request.isSecure()));
    }

    return new ModelAndView(rss ? "view-message-rss" : "view-message", params);
}

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

/**
 * Preprocess the request. This will:// w  ww . java  2  s.co  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:ru.org.linux.topic.EditTopicController.java

@RequestMapping(value = "/commit.jsp", method = RequestMethod.GET)
public ModelAndView showCommitForm(HttpServletRequest request, @RequestParam("msgid") int msgid,
        @ModelAttribute("form") EditTopicRequest form) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
        throw new AccessViolationException("Not authorized");
    }//from ww w . j  a  va2  s . c o  m

    Topic message = messageDao.getById(msgid);

    if (message.isCommited()) {
        throw new UserErrorException("  ");
    }

    PreparedTopic preparedMessage = messagePrepareService.prepareMessage(message, false, request.isSecure());

    if (!preparedMessage.getSection().isPremoderated()) {
        throw new UserErrorException("  ");
    }

    ModelAndView mv = prepareModel(preparedMessage, form);

    mv.getModel().put("commit", true);

    return mv;
}