Example usage for javax.servlet.http HttpServletResponse isCommitted

List of usage examples for javax.servlet.http HttpServletResponse isCommitted

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse isCommitted.

Prototype

public boolean isCommitted();

Source Link

Document

Returns a boolean indicating if the response has been committed.

Usage

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackOAuthWindowsLiveController.java

@RequestMapping("/callback-oauth-windows-live.html*")
public ModelAndView callBackWindowsLive(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {//from  w ww.  j a va2s  .c o m

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getSettingOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.WINDOWS_LIVE.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getSettingOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.WINDOWS_LIVE.name());

            // CLIENT PERMISSIONS
            EngineSetting permissionsEngineSetting = engineSettingService.getSettingOAuthAppPermissions();
            EngineSettingValue permissionsEngineSettingValue = permissionsEngineSetting
                    .getEngineSettingValue(OAuthType.WINDOWS_LIVE.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null
                    && permissionsEngineSettingValue != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();
                final String permissions = permissionsEngineSettingValue.getValue();

                final String windowsLiveCallBackURL = urlService.buildAbsoluteUrl(requestData,
                        urlService.buildOAuthCallBackUrl(requestData,
                                OAuthType.WINDOWS_LIVE.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(LiveApi.class).apiKey(clientId)
                        .apiSecret(clientSecret).scope(permissions).callback(windowsLiveCallBackURL).build();

                final String code = request.getParameter("code");
                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
                    OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, LIVE_ME_URL);
                    service.signRequest(accessToken, oauthRequest);
                    Response oauthResponse = oauthRequest.send();
                    int responseCode = oauthResponse.getCode();
                    String responseBody = oauthResponse.getBody();

                    if (responseCode == 200) {
                        handleAuthenticationData(request, response, requestData, OAuthType.WINDOWS_LIVE,
                                responseBody);
                    } else {
                        logger.error("Callback With " + OAuthType.WINDOWS_LIVE.name() + " failed!");
                    }
                } else {
                    logger.error("Callback With " + OAuthType.WINDOWS_LIVE.name() + " failed!");
                }

            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.WINDOWS_LIVE.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackOAuthGoogleAccountController.java

@RequestMapping("/callback-oauth-google-account.html*")
public ModelAndView callBackGoogleAccount(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {/*from   w ww .ja  v a2  s .c o m*/

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getSettingOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getSettingOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            // CLIENT PERMISSIONS
            EngineSetting permissionsEngineSetting = engineSettingService.getSettingOAuthAppPermissions();
            EngineSettingValue permissionsEngineSettingValue = permissionsEngineSetting
                    .getEngineSettingValue(OAuthType.GOOGLE_ACCOUNT.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null
                    && permissionsEngineSettingValue != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();
                final String permissions = permissionsEngineSettingValue.getValue();

                final String googleAccountCallBackURL = urlService.buildAbsoluteUrl(requestData,
                        urlService.buildOAuthCallBackUrl(requestData,
                                OAuthType.GOOGLE_ACCOUNT.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(clientId)
                        .apiSecret(clientSecret).scope(permissions).callback(googleAccountCallBackURL).build();

                final String code = request.getParameter("code");
                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
                    OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, GOOGLE_ME_URL);
                    service.signRequest(accessToken, oauthRequest);
                    Response oauthResponse = oauthRequest.send();
                    int responseCode = oauthResponse.getCode();
                    String responseBody = oauthResponse.getBody();

                    if (responseCode == 200) {
                        handleAuthenticationData(request, response, requestData, OAuthType.GOOGLE_ACCOUNT,
                                responseBody);
                    } else {
                        logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
                    }
                } else {
                    logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
                }
            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.GOOGLE_ACCOUNT.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param request/*from w  ww. ja  va 2  s.c  o  m*/
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 * @param content
 *          Should the content be included?
 *
 * @exception IOException
 *              if an input/output error occurs
 * @exception ServletException
 *              if a servlet-specified error occurs
 */
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    boolean serveContent = content;

    // Identify the requested resource path
    String sessionId = extractSessionId(request);

    RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId);

    if (elem == null) {

        if (debug > 0) {
            log("Resource with sessionId '" + sessionId + "' not found");
        }

        response.sendError(SC_NOT_FOUND, request.getRequestURI());
        return;
    }

    elem.fireStartedEventIfFirstTime();

    RepositoryItem repositoryItem = elem.getRepositoryItem();
    RepositoryItemAttributes attributes = repositoryItem.getAttributes();

    if (debug > 0) {
        if (serveContent) {
            log("Serving resource with sessionId '" + sessionId
                    + "' headers and data. This resource corresponds to repository item '"
                    + repositoryItem.getId() + "'");
        } else {
            log("Serving resource with sessionId '" + sessionId
                    + "' headers only. This resource corresponds to repository item '" + repositoryItem.getId()
                    + "'");
        }
    }

    boolean malformedRequest = response.getStatus() >= SC_BAD_REQUEST;

    if (!malformedRequest && !checkIfHeaders(request, response, attributes)) {
        return;
    }

    String contentType = getContentType(elem, attributes);

    List<Range> ranges = null;

    if (!malformedRequest) {

        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", attributes.getETag());
        response.setHeader("Last-Modified", attributes.getLastModifiedHttp());

        ranges = parseRange(request, response, attributes);
    }

    long contentLength = attributes.getContentLength();

    // Special case for zero length files, which would cause a
    // (silent) ISE when setting the output buffer size
    if (contentLength == 0L) {
        serveContent = false;
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    boolean contentWritten = response.isCommitted();

    if (contentWritten) {
        ranges = FULL;
    }

    boolean noRanges = ranges == null || ranges.isEmpty();

    if (malformedRequest || noRanges && request.getHeader("Range") == null || ranges == FULL) {

        setContentType(response, contentType);

        if (contentLength >= 0) {
            // Don't set a content length if something else has already
            // written to the response.
            if (!contentWritten) {
                setContentLength(response, contentLength);
            }
        }

        // Copy the input stream to our output stream (if requested)
        if (serveContent) {
            copy(elem, response);
        }

    } else {

        if (noRanges) {
            return;
        }

        // Partial content response.
        response.setStatus(SC_PARTIAL_CONTENT);

        if (ranges.size() == 1) {

            Range range = ranges.get(0);

            response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);

            long length = range.end - range.start + 1;

            setContentLength(response, length);
            setContentType(response, contentType);

            if (serveContent) {
                copy(elem, response, range);
            }

        } else {

            response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION);

            if (serveContent) {
                copy(elem, response, ranges, contentType);
            }
        }
    }

    elem.stopInTimeout();

}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

/**
 * Serve the specified resource, optionally including the data content.
 * /*from  w w w  .ja  va 2  s . c  o  m*/
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param content
 *            Should the content be included?
 * 
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet-specified error occurs
 */
protected void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    boolean serveContent = content;

    // Identify the requested resource path
    String sessionId = extractSessionId(request);

    RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId);

    if (elem == null) {

        if (debug > 0) {
            log("Resource with sessionId '" + sessionId + "' not found");
        }

        response.sendError(SC_NOT_FOUND, request.getRequestURI());
        return;
    }

    elem.fireStartedEventIfFirstTime();

    RepositoryItem repositoryItem = elem.getRepositoryItem();
    RepositoryItemAttributes attributes = repositoryItem.getAttributes();

    if (debug > 0) {
        if (serveContent) {
            log("Serving resource with sessionId '" + sessionId
                    + "' headers and data. This resource corresponds to repository item '"
                    + repositoryItem.getId() + "'");
        } else {
            log("Serving resource with sessionId '" + sessionId
                    + "' headers only. This resource corresponds to repository item '" + repositoryItem.getId()
                    + "'");
        }
    }

    boolean malformedRequest = response.getStatus() >= SC_BAD_REQUEST;

    if (!malformedRequest && !checkIfHeaders(request, response, attributes)) {
        return;
    }

    String contentType = getContentType(elem, attributes);

    List<Range> ranges = null;

    if (!malformedRequest) {

        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", attributes.getETag());
        response.setHeader("Last-Modified", attributes.getLastModifiedHttp());

        ranges = parseRange(request, response, attributes);
    }

    long contentLength = attributes.getContentLength();

    // Special case for zero length files, which would cause a
    // (silent) ISE when setting the output buffer size
    if (contentLength == 0L) {
        serveContent = false;
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    boolean contentWritten = response.isCommitted();

    if (contentWritten) {
        ranges = FULL;
    }

    boolean noRanges = (ranges == null || ranges.isEmpty());

    if (malformedRequest || (noRanges && request.getHeader("Range") == null) || ranges == FULL) {

        setContentType(response, contentType);

        if (contentLength >= 0) {
            // Don't set a content length if something else has already
            // written to the response.
            if (!contentWritten) {
                setContentLength(response, contentLength);
            }
        }

        // Copy the input stream to our output stream (if requested)
        if (serveContent) {
            copy(elem, response);
        }

    } else {

        if (noRanges) {
            return;
        }

        // Partial content response.
        response.setStatus(SC_PARTIAL_CONTENT);

        if (ranges.size() == 1) {

            Range range = ranges.get(0);

            response.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);

            long length = range.end - range.start + 1;

            setContentLength(response, length);
            setContentType(response, contentType);

            if (serveContent) {
                copy(elem, response, range);
            }

        } else {

            response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION);

            if (serveContent) {
                copy(elem, response, ranges, contentType);
            }
        }
    }

    elem.stopInTimeout();

}

From source file:it.classhidra.core.controller.bsController.java

public static HttpServletResponse execRedirect(i_action action_instance, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response, boolean allowAnotherOutput)
        throws bsControllerException, ServletException, UnavailableException {

    if (action_instance == null || action_instance.get_infoaction() == null)
        return response;
    boolean intoWrapper = false;
    Object[] resultC4AOutputMode = chech4AnotherOutputMode(action_instance, servletContext, request, response,
            allowAnotherOutput);/*from   w  ww. j a v  a2 s . c o m*/

    if (((Boolean) resultC4AOutputMode[1]).booleanValue()) {
        return response;
    }

    if (resultC4AOutputMode[0] instanceof a_ResponseWrapper) {
        response = (a_ResponseWrapper) resultC4AOutputMode[0];
        intoWrapper = true;
    }

    action_instance.onPreRedirect();
    RequestDispatcher rd = action_instance.getCurrent_redirect().redirect(servletContext,
            action_instance.get_infoaction());
    action_instance.onPostRedirect(rd);

    if (rd == null) {
        action_instance.onPreRedirectError();

        rd = action_instance.getCurrent_redirect().redirectError(servletContext,
                action_instance.get_infoaction());
        action_instance.onPostRedirectError(rd);
    }
    if (rd == null) {
        if (!action_instance.get_infoaction().getError().equals(""))
            action_instance.getCurrent_redirect().set_uriError(action_instance.get_infoaction().getError());
        else
            action_instance.getCurrent_redirect().set_uriError(getAction_config().getAuth_error());
        rd = action_instance.getCurrent_redirect().redirectError(servletContext,
                action_instance.get_infoaction());
    }

    if (rd == null)
        throw new bsControllerException("Controller generic redirect error. Action: ["
                + action_instance.get_infoaction().getPath() + "] " + action_instance.getCurrent_redirect(),
                request, iStub.log_ERROR);
    else {
        try {
            try {
                action_instance.actionBeforeRedirect(request, response);
            } catch (Exception e) {
                throw new bsControllerException(
                        "Controller generic actionBeforeRedirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        request, iStub.log_ERROR);
            }

            if (!intoWrapper) {

                if (!action_instance.isIncluded()) {
                    if (response.isCommitted())
                        rd.include(request, response);
                    else
                        rd.forward(request, response);
                } else
                    rd.include(request, response);

            } else {

                String tansformationElaborationMode = getAppInit().get_transf_elaborationmode();

                if (tansformationElaborationMode == null || tansformationElaborationMode.trim().length() == 0)
                    tansformationElaborationMode = CONST_TRANSFORMATION_ELMODE_INCLUDE;

                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_BOTH)) {
                    if (response.isCommitted())
                        rd.include(request, response);
                    else
                        rd.forward(request, response);
                }
                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_INCLUDE)) {
                    rd.include(request, response);
                }
                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_FORWARD)) {
                    rd.forward(request, response);
                }

            }

        } catch (Exception e) {
            if (intoWrapper) {
                throw new bsControllerException(
                        "Controller generic wrapped redirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        iStub.log_ERROR);
            } else
                throw new bsControllerException(
                        "Controller generic redirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        request, iStub.log_ERROR);
        }
    }
    return response;
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

/**
 * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
 *
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
 *
 * @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.
 *//*from   w  w  w  .j a v a  2  s  .c om*/
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper,
        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());
    AuthenticationHandler authHandler = getAuthenticationHandler();
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: {}", ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 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 (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }

                filterChainWrapper.doFilter(httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, 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) { // added this code for atlas error handling and fallback
                if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKrbFilter.java

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object./*  w  w  w  .jav  a  2s .  c om*/
 * @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.
 */
@Override
public void doFilter(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);
        } catch (AuthenticationException ex) {
            ex.printStackTrace();
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 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 (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        ex.printStackTrace();
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, 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) {
                String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM,
                        RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
                if (agents == null) {
                    agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT;
                }
                parseBrowserUserAgents(agents);
                if (isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT))) {
                    ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, "");
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie")
                                && value.startsWith("RANGERADMINSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.hoteia.qalingo.core.web.mvc.controller.oauth.CallBackOAuthFacebookController.java

@RequestMapping("/callback-oauth-facebook.html*")
public ModelAndView callBackFacebook(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    final RequestData requestData = requestUtil.getRequestData(request);

    // SANITY CHECK
    if (!requestUtil.hasKnownCustomerLogged(request)) {
        try {//from   w ww .j  a  v  a2  s  . co  m

            // CLIENT ID
            EngineSetting clientIdEngineSetting = engineSettingService.getSettingOAuthAppKeyOrId();
            EngineSettingValue clientIdEngineSettingValue = clientIdEngineSetting
                    .getEngineSettingValue(OAuthType.FACEBOOK.name());

            // CLIENT SECRET
            EngineSetting clientSecretEngineSetting = engineSettingService.getSettingOAuthAppSecret();
            EngineSettingValue clientSecretEngineSettingValue = clientSecretEngineSetting
                    .getEngineSettingValue(OAuthType.FACEBOOK.name());

            // CLIENT PERMISSIONS
            EngineSetting permissionsEngineSetting = engineSettingService.getSettingOAuthAppPermissions();
            EngineSettingValue permissionsEngineSettingValue = permissionsEngineSetting
                    .getEngineSettingValue(OAuthType.FACEBOOK.name());

            if (clientIdEngineSettingValue != null && clientSecretEngineSetting != null
                    && permissionsEngineSettingValue != null) {
                final String clientId = clientIdEngineSettingValue.getValue();
                final String clientSecret = clientSecretEngineSettingValue.getValue();
                final String permissions = permissionsEngineSettingValue.getValue();

                final String facebookCallBackURL = urlService.buildAbsoluteUrl(requestData, urlService
                        .buildOAuthCallBackUrl(requestData, OAuthType.FACEBOOK.getPropertyKey().toLowerCase()));

                OAuthService service = new ServiceBuilder().provider(FacebookApi.class).apiKey(clientId)
                        .apiSecret(clientSecret).scope(permissions).callback(facebookCallBackURL).build();

                final String code = request.getParameter("code");

                final String informationUrl = FACEBOOK_ME_URL
                        + "?fields=id,name,first_name,last_name,link,website,gender,locale,about,email,hometown,location";

                if (StringUtils.isNotEmpty(code)) {
                    Verifier verifier = new Verifier(code);
                    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
                    OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, informationUrl);
                    service.signRequest(accessToken, oauthRequest);
                    Response oauthResponse = oauthRequest.send();
                    int responseCode = oauthResponse.getCode();
                    String responseBody = oauthResponse.getBody();

                    if (responseCode == 200) {
                        handleAuthenticationData(request, response, requestData, OAuthType.FACEBOOK,
                                responseBody);
                    } else {
                        logger.error("Callback With " + OAuthType.FACEBOOK.name() + " failed!");
                    }
                } else {
                    logger.error("Callback With " + OAuthType.FACEBOOK.name() + " failed!");
                }

            }

        } catch (Exception e) {
            logger.error("Callback With " + OAuthType.FACEBOOK.name() + " failed!");
        }
    }

    // DEFAULT FALLBACK VALUE
    if (!response.isCommitted()) {
        response.sendRedirect(urlService.generateUrl(FoUrls.LOGIN, requestData));
    }

    return null;
}

From source file:org.alfresco.web.app.servlet.CommandServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  ww  w .j a  va2s .  c  om*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String uri = req.getRequestURI();

    if (logger.isDebugEnabled())
        logger.debug(
                "Processing URL: " + uri + (req.getQueryString() != null ? ("?" + req.getQueryString()) : ""));

    AuthenticationStatus status = servletAuthenticate(req, res);
    if (status == AuthenticationStatus.Failure) {
        return;
    }

    setNoCacheHeaders(res);

    uri = uri.substring(req.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    int tokenCount = t.countTokens();
    if (tokenCount < 3) {
        throw new IllegalArgumentException("Command Servlet URL did not contain all required args: " + uri);
    }

    t.nextToken(); // skip servlet name

    // get the command processor to execute the command e.g. "workflow"
    String procName = t.nextToken();

    // get the command to perform
    String command = t.nextToken();

    // get any remaining uri elements to pass to the processor
    String[] urlElements = new String[tokenCount - 3];
    for (int i = 0; i < tokenCount - 3; i++) {
        urlElements[i] = t.nextToken();
    }

    // retrieve the URL arguments to pass to the processor
    Map<String, String> args = new HashMap<String, String>(8, 1.0f);
    Enumeration names = req.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        args.put(name, req.getParameter(name));
    }

    try {
        // get configured command processor by name from Config Service
        CommandProcessor processor = createCommandProcessor(procName);

        // validate that the processor has everything it needs to run the command
        if (processor.validateArguments(getServletContext(), command, args, urlElements) == false) {
            redirectToLoginPage(req, res, getServletContext());
            return;
        }

        ServiceRegistry serviceRegistry = getServiceRegistry(getServletContext());
        UserTransaction txn = null;
        try {
            txn = serviceRegistry.getTransactionService().getUserTransaction();
            txn.begin();

            // inform the processor to execute the specified command
            if (processor instanceof ExtCommandProcessor) {
                ((ExtCommandProcessor) processor).process(serviceRegistry, req, res, command);
            } else {
                processor.process(serviceRegistry, req, command);
            }

            // commit the transaction
            txn.commit();
        } catch (Throwable txnErr) {
            try {
                if (txn != null) {
                    txn.rollback();
                }
            } catch (Exception tex) {
            }
            throw txnErr;
        }

        String returnPage = req.getParameter(ARG_RETURNPAGE);
        if (returnPage != null && returnPage.length() != 0) {
            validateReturnPage(returnPage, req);
            if (logger.isDebugEnabled())
                logger.debug("Redirecting to specified return page: " + returnPage);

            res.sendRedirect(returnPage);
        } else {
            if (logger.isDebugEnabled())
                logger.debug("No return page specified, displaying status output.");

            if (res.getContentType() == null && !res.isCommitted()) {
                res.setContentType("text/html");

                // request that the processor output a useful status message
                PrintWriter out = res.getWriter();
                processor.outputStatus(out);
                out.close();
            }
        }
    } catch (Throwable err) {
        throw new AlfrescoRuntimeException("Error during command servlet processing: " + err.getMessage(), err);
    }
}

From source file:org.ops4j.pax.web.resources.jsf.OsgiResourceHandler.java

@Override
public void handleResourceRequest(FacesContext facesContext) throws IOException {
    final Map<String, String> requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
    if (!"osgi".equals(requestParameterMap.get(OsgiResource.REQUEST_PARAM_TYPE))) {
        // no OsgiResource...proceed with default ResourceHandler
        super.handleResourceRequest(facesContext);
    }/* ww w. j  a va 2 s . c om*/

    String localePrefix = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LOCALE);
    String libraryName = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY);
    String libraryVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_LIBRARY_VERSION);
    String resourceVersion = requestParameterMap.get(OsgiResource.REQUEST_PARAM_RESOURCE_VERSION);

    String resourceBasePath = ResourceHandlerUtils.calculateResourceBasePath(facesContext);

    if (resourceBasePath == null) {
        // No base name could be calculated, so no further
        //advance could be done here. HttpServletResponse.SC_NOT_FOUND
        //cannot be returned since we cannot extract the
        //resource base name
        return;
    }

    // We neet to get an instance of HttpServletResponse, but sometimes
    // the response object is wrapped by several instances of
    // ServletResponseWrapper (like ResponseSwitch).
    // Since we are handling a resource, we can expect to get an
    // HttpServletResponse.
    HttpServletResponse httpServletResponse = ResourceHandlerUtils
            .getHttpServletResponse(facesContext.getExternalContext().getResponse());
    if (httpServletResponse == null) {
        throw new IllegalStateException("Could not obtain an instance of HttpServletResponse.");
    }

    if (ResourceHandlerUtils.isResourceIdentifierExcluded(facesContext, resourceBasePath,
            excludedResourceExtensions)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // extract resourceName. if none was found set Response to 404
    String resourceName;
    if (resourceBasePath.startsWith(ResourceHandler.RESOURCE_IDENTIFIER)) {
        resourceName = resourceBasePath.substring(ResourceHandler.RESOURCE_IDENTIFIER.length() + 1);

        if (!ResourceValidationUtils.isValidResourceName(resourceName)) {
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    } else {
        //Does not have the conditions for be a resource call
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (libraryName != null && !ResourceValidationUtils.isValidLibraryName(libraryName)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    String resourceIdentifier = createResourceIdentifier(localePrefix, resourceName, resourceVersion,
            libraryName, libraryVersion);

    OsgiResource resource;
    // in this case we have the full path to the resource, no version-magic needed
    ResourceInfo resourceInfo = getServiceAndExecute(service -> service.locateResource(resourceIdentifier));
    if (resourceInfo == null) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    resource = new OsgiResource(resourceInfo.getUrl(), localePrefix, resourceName, resourceVersion, libraryName,
            libraryVersion, resourceInfo.getLastModified());

    // Resource has not changed, return 304
    if (!resource.userAgentNeedsUpdate(facesContext)) {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // serve

    httpServletResponse
            .setContentType(ResourceHandlerUtils.getContentType(resource, facesContext.getExternalContext()));

    Map<String, String> headers = resource.getResponseHeaders();

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpServletResponse.setHeader(entry.getKey(), entry.getValue());
    }

    // Sets the preferred buffer size for the body of the response
    facesContext.getExternalContext().setResponseBufferSize(this.resourceBufferSize);

    //serve up the bytes (taken from trinidad ResourceServlet)
    try {

        //byte[] buffer = new byte[_BUFFER_SIZE];
        byte[] buffer = new byte[this.resourceBufferSize];

        try (InputStream in = resource.getInputStream();
                OutputStream out = httpServletResponse.getOutputStream()) {
            int count = ResourceHandlerUtils.pipeBytes(in, out, buffer);
            //set the content length
            if (!httpServletResponse.isCommitted()) {
                httpServletResponse.setContentLength(count);
            }
        }
    } catch (IOException e) {
        if (logger.isErrorEnabled()) {
            logger.error("Error trying to load resource '{}' with library '{}' : {}",
                    new Object[] { resourceName, libraryName, e.getMessage(), e });
        }
        // return 404
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }

}