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:com.globalsight.everest.webapp.pagehandler.administration.workflow.WorkflowTemplateHandler.java

public void sendFileToClient(HttpServletRequest request, HttpServletResponse response, String zipFileName,
        File workflowXml) {//w  w  w . j  a v  a2s.  com
    if (request.isSecure()) {
        PageHandler.setHeaderForHTTPSDownload(response);
    }
    FileInputStream fis = null;
    try {
        response.setContentType("application/zip");
        String attachment = "attachment; filename=\"" + UrlUtil.encode(zipFileName, "utf-8") + "\";";
        response.setHeader("Content-Disposition", attachment);
        response.setContentLength((int) workflowXml.length());
        byte[] inBuff = new byte[4096];
        fis = new FileInputStream(workflowXml);
        int bytesRead = 0;
        while ((bytesRead = fis.read(inBuff)) != -1) {
            response.getOutputStream().write(inBuff, 0, bytesRead);
        }

        if (bytesRead > 0) {
            response.getOutputStream().write(inBuff, 0, bytesRead);
        }

        fis.close();
    } catch (IOException e) {
        CATEGORY.error(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                CATEGORY.error(e);
            }
        }
    }

}

From source file:com.frameworkset.platform.cms.driver.url.impl.CMSURLParserImpl.java

/**
 * Parse a servlet request to a portal URL.
 * @param request  the servlet request to parse.
 * @return the portal URL.//from w w  w.  j av  a 2  s . c o  m
 */
public CMSURL parse(HttpServletRequest request) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing URL: " + request.getRequestURI());
    }

    String protocol = request.isSecure() ? "https://" : "http://";
    String server = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getContextPath();
    String servletName = request.getServletPath();

    // Construct portal URL using info retrieved from servlet request.
    CMSURL portalURL = null;
    if ((request.isSecure() && port != 443) || (!request.isSecure() && port != 80)) {
        portalURL = new CMSURLImpl(protocol, server, port, contextPath, servletName);
    } else {
        portalURL = new CMSURLImpl(protocol, server, contextPath, servletName);
    }

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return portalURL;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing request pathInfo: " + pathInfo);
    }
    StringBuffer renderPath = new StringBuffer();
    StringTokenizer st = new StringTokenizer(pathInfo, "/", false);
    while (st.hasMoreTokens()) {

        String token = st.nextToken();

        // Part of the render path: append to renderPath.
        if (!token.startsWith(PREFIX)) {
            //              renderPath.append(token);
            //Fix for PLUTO-243
            renderPath.append('/').append(token);
        }
        // Action window definition: portalURL.setActionWindow().
        else if (token.startsWith(PREFIX + ACTION)) {
            portalURL.setActionWindow(decodeControlParameter(token)[0]);
        }
        // Window state definition: portalURL.setWindowState().
        else if (token.startsWith(PREFIX + WINDOW_STATE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setWindowState(decoded[0], new WindowState(decoded[1]));
        }
        // Portlet mode definition: portalURL.setPortletMode().
        else if (token.startsWith(PREFIX + PORTLET_MODE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setPortletMode(decoded[0], new PortletMode(decoded[1]));
        }
        // Portal URL parameter: portalURL.addParameter().
        else {
            String value = null;
            if (st.hasMoreTokens()) {
                value = st.nextToken();
            }
            portalURL.addParameter(decodeParameter(token, value));
        }
    }
    if (renderPath.length() > 0) {
        portalURL.setRenderPath(renderPath.toString());
    }

    // Return the portal URL.
    return portalURL;
}

From source file:org.pentaho.cdf.CdfApi.java

public void buildCdfEmbedContext(@QueryParam("protocol") String protocol, @QueryParam("name") String name,
        @QueryParam("port") int port, @QueryParam("inactiveInterval") int inactiveInterval,
        @QueryParam("locale") String locale, @Context HttpServletRequest servletRequest,
        @Context HttpServletResponse servletResponse) throws Exception {
    buildCdfEmbedContextSecure(protocol, name, port, inactiveInterval, locale, servletRequest.isSecure(),
            servletRequest, servletResponse);
}

From source file:com.acc.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null && !modelAndView.getModel().containsKey("metaRobots")) {
        // Build a default directive
        String robotsValue = "no-index,no-follow";

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = "no-index,follow";
            }/*w w w  .j a va2s. co  m*/
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = "index,follow";
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = "no-index,no-follow";
        }

        modelAndView.addObject("metaRobots", robotsValue);
    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get("metaRobots"));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:com.exxonmobile.ace.hybris.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null && !modelAndView.getModel().containsKey("metaRobots")) {
        // Build a default directive
        String robotsValue = "no-index,no-follow";

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = "no-index,follow";
            }/*w w  w .  j a v  a 2 s . co  m*/
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = "index,follow";
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = "no-index,no-follow";
        }

        modelAndView.addObject("metaRobots", robotsValue);

    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get("metaRobots"));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:org.projectforge.web.UserFilter.java

/**
 * User is not logged. Checks a stay-logged-in-cookie.
 * @return user if valid cookie found, otherwise null.
 */// w w  w .  j  a  v a2s.co m
private PFUserDO checkStayLoggedIn(final HttpServletRequest request, final HttpServletResponse response) {
    final Cookie sessionIdCookie = getCookie(request, "JSESSIONID");
    if (sessionIdCookie != null && sessionIdCookie.getSecure() == false && request.isSecure() == true) {
        // Hack for developers: Safari (may-be also other browsers) don't update unsecure cookies for secure connections. This seems to be
        // occurring
        // if you use ProjectForge on localhost with http and https (e. g. for testing). You have to delete this cookie normally in your
        // browser.
        final Cookie cookie = new Cookie("JSESSIONID", "to be deleted");
        cookie.setMaxAge(0);
        cookie.setPath(sessionIdCookie.getPath()); // Doesn't work for Safari: getPath() returns always null!
        response.addCookie(cookie);
    }
    final Cookie stayLoggedInCookie = getStayLoggedInCookie(request);
    if (stayLoggedInCookie != null) {
        final String value = stayLoggedInCookie.getValue();
        if (StringUtils.isBlank(value) == true) {
            return null;
        }
        final String[] values = value.split(":");
        if (values == null || values.length != 3) {
            log.warn("Invalid cookie found: " + value);
            return null;
        }
        final Integer userId = NumberHelper.parseInteger(values[0]);
        final PFUserDO user = userDao.internalGetById(userId);
        if (user == null) {
            log.warn("Invalid cookie found (user not found): " + value);
            return null;
        }
        if (user.getUsername().equals(values[1]) == false) {
            log.warn("Invalid cookie found (user name wrong, maybe changed): " + value);
            return null;
        }
        if (values[2] == null || values[2].equals(user.getStayLoggedInKey()) == false) {
            log.warn("Invalid cookie found (stay-logged-in key, maybe renewed and/or user password changed): "
                    + value);
            return null;
        }
        if (Login.getInstance().checkStayLoggedIn(user) == false) {
            log.warn("Stay-logged-in wasn't accepted by the login handler: " + user.getUserDisplayname());
            return null;
        }
        addStayLoggedInCookie(request, response, stayLoggedInCookie);
        log.info("User successfully logged in using stay-logged-in method: " + user.getUserDisplayname());
        return user;
    }
    return null;
}

From source file:org.apache.nifi.web.api.AccessResource.java

/**
 * Creates a single use access token for downloading FlowFile content.
 *
 * @param httpServletRequest the servlet request
 * @return A token (string)//from ww w.ja va  2 s  .c  o m
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Path("/download-token")
@ApiOperation(value = "Creates a single use access token for downloading FlowFile content.", notes = "The token returned is a base64 encoded string. It is valid for a single request up to five minutes from being issued. "
        + "It is used as a query parameter name 'access_token'.", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 409, message = "Unable to create the download token because NiFi is not in the appropriate state. "
                + "(i.e. may not have any tokens to grant or be configured to support username/password login)"),
        @ApiResponse(code = 500, message = "Unable to create download token because an unexpected error occurred.") })
public Response createDownloadToken(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Download tokens are only issued over HTTPS.");
    }

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new AccessDeniedException("No user authenticated in the request.");
    }

    final OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(user.getIdentity());

    // generate otp for response
    final String token = otpService.generateDownloadToken(authenticationToken);

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "download-token"));
    return generateCreatedResponse(uri, token).build();
}

From source file:org.apache.nifi.web.api.AccessResource.java

/**
 * Creates a single use access token for accessing a NiFi UI extension.
 *
 * @param httpServletRequest the servlet request
 * @return A token (string)/* w w  w  . j a va2 s . c  o m*/
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Path("/ui-extension-token")
@ApiOperation(value = "Creates a single use access token for accessing a NiFi UI extension.", notes = "The token returned is a base64 encoded string. It is valid for a single request up to five minutes from being issued. "
        + "It is used as a query parameter name 'access_token'.", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 409, message = "Unable to create the download token because NiFi is not in the appropriate state. "
                + "(i.e. may not have any tokens to grant or be configured to support username/password login)"),
        @ApiResponse(code = 500, message = "Unable to create download token because an unexpected error occurred.") })
public Response createUiExtensionToken(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("UI extension access tokens are only issued over HTTPS.");
    }

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new AccessDeniedException("No user authenticated in the request.");
    }

    final OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(user.getIdentity());

    // generate otp for response
    final String token = otpService.generateUiExtensionToken(authenticationToken);

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "ui-extension-token"));
    return generateCreatedResponse(uri, token).build();
}

From source file:org.wso2.carbon.event.input.adapter.http.HTTPMessageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String data = this.inputStreamToString(req.getInputStream());
    if (data == null) {
        log.warn("Event Object is empty/null");
        return;/*ww  w .java 2 s  .c  om*/
    }

    if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTPS)) {
        if (!req.isSecure()) {
            res.setStatus(403);
            log.error("Only Secured endpoint is enabled for requests");
            return;
        } else {
            if (isBasicAuthEnabled) {
                int tenantId = this.checkAuthentication(req);
                if (tenantId == -1) {
                    res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                    res.setStatus(401);
                    log.error("Authentication failed for the request");
                    return;
                } else if (tenantId != this.tenantId) {
                    res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                    res.setStatus(401);
                    log.error("Authentication failed for the request");
                    return;
                }
            }
        }
    } else if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTP)) {
        if (req.isSecure()) {
            res.setStatus(403);
            log.error("Only unsecured endpoint is enabled for requests");
            return;
        }
    } else {
        if (req.isSecure()) {
            if (isBasicAuthEnabled) {
                int tenantId = this.checkAuthentication(req);
                if (tenantId == -1) {
                    res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                    res.setStatus(401);
                    log.error("Authentication failed for the request");
                    return;
                } else if (tenantId != this.tenantId) {
                    res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                    res.setStatus(401);
                    log.error("Authentication failed for the request");
                    return;
                }
            }
        }

    }

    if (log.isDebugEnabled()) {
        log.debug("Message : " + data);
    }
    HTTPEventAdapter.executorService.submit(new HTTPRequestProcessor(eventAdaptorListener, data, tenantId));

}

From source file:org.broadleafcommerce.profile.web.core.security.SessionFixationProtectionFilter.java

@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) sRequest;
    HttpServletResponse response = (HttpServletResponse) sResponse;
    HttpSession session = request.getSession(false);

    if (SecurityContextHolder.getContext() == null) {
        chain.doFilter(request, response);
    }// w w w .  j av  a2 s. c o m

    String activeIdSessionValue = (session == null) ? null : (String) session.getAttribute(SESSION_ATTR);

    if (StringUtils.isNotBlank(activeIdSessionValue) && request.isSecure()) {
        // The request is secure and and we've set a session fixation protection cookie

        String activeIdCookieValue = cookieUtils.getCookieValue(request,
                SessionFixationProtectionCookie.COOKIE_NAME);
        String decryptedActiveIdValue = encryptionModule.decrypt(activeIdCookieValue);

        if (!activeIdSessionValue.equals(decryptedActiveIdValue)) {
            abortUser(request, response);
            LOG.info("Session has been terminated. ActiveID did not match expected value.");
            return;
        }
    } else if (request.isSecure() && session != null) {
        // If there is no session (session == null) then there isn't anything to worry about

        // The request is secure, but we haven't set a session fixation protection cookie yet
        String token;
        try {
            token = RandomGenerator.generateRandomId("SHA1PRNG", 32);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException(e);
        }

        String encryptedActiveIdValue = encryptionModule.encrypt(token);

        session.setAttribute(SESSION_ATTR, token);
        cookieUtils.setCookieValue(response, SessionFixationProtectionCookie.COOKIE_NAME,
                encryptedActiveIdValue, "/", -1, true);
    }

    chain.doFilter(request, response);
}