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.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsControllerHelper.java

public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
    if (uri == null) {
        throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
    }/*from   w  w w  .  java 2  s  . c o  m*/
    HttpServletRequest request = webRequest.getCurrentRequest();
    HttpServletResponse response = webRequest.getCurrentResponse();

    configureStateForWebRequest(webRequest, request);

    if (uri.endsWith("/")) {
        uri = uri.substring(0, uri.length() - 1);
    }

    // if the id is blank check if its a request parameter

    // Step 2: lookup the controller in the application.
    GrailsControllerClass controllerClass = getControllerClassByURI(uri);

    if (controllerClass == null) {
        throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
    }

    actionName = controllerClass.getClosurePropertyName(uri);
    webRequest.setActionName(actionName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing request for controller [" + controllerName + "], action [" + actionName
                + "], and id [" + id + "]");
    }
    controllerActionURI = SLASH + controllerName + SLASH + actionName + SLASH;

    // Step 3: load controller from application context.
    GroovyObject controller = getControllerInstance(controllerClass);

    if (!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
        try {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return null;
        } catch (IOException e) {
            throw new ControllerExecutionException("I/O error sending 403 error", e);
        }
    }

    request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller);

    // Step 4: Set grails attributes in request scope
    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, this.grailsAttributes);

    // Step 5: get the view name for this URI.
    String viewName = controllerClass.getViewByURI(uri);

    boolean executeAction = invokeBeforeInterceptor(controller, controllerClass);
    // if the interceptor returned false don't execute the action
    if (!executeAction)
        return null;

    ModelAndView mv = executeAction(controller, controllerClass, viewName, request, response, params);

    boolean returnModelAndView = invokeAfterInterceptor(controllerClass, controller, mv)
            && !response.isCommitted();
    return returnModelAndView ? mv : null;
}

From source file:de.qucosa.dissemination.epicur.servlet.EpicurDisseminationServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    URI metsDocumentUri;/* w w  w  . ja  v a  2s .c  o m*/
    boolean transferUrlPidencode;
    String transferUrlPattern;
    String frontpageUrlPattern;
    Map<String, String> agentNameSubstitutions;
    try {
        String reqParameter = req.getParameter(REQUEST_PARAM_METS_URL);
        if (reqParameter == null || reqParameter.isEmpty()) {
            resp.sendError(SC_BAD_REQUEST, "Missing parameter '" + REQUEST_PARAM_METS_URL + "'");
            return;
        }
        metsDocumentUri = URI.create(reqParameter);

        ServletConfig config = getServletConfig();

        transferUrlPattern = getParameterValue(config, PARAM_TRANSFER_URL_PATTERN);
        frontpageUrlPattern = getParameterValue(config, PARAM_FRONTPAGE_URL_PATTERN);
        transferUrlPidencode = isParameterSet(config, PARAM_TRANSFER_URL_PIDENCODE);

        agentNameSubstitutions = decodeSubstitutions(getParameterValue(config, PARAM_AGENT_NAME_SUBSTITUTIONS));

    } catch (Exception e) {
        log.error(e.getMessage());
        resp.sendError(SC_INTERNAL_SERVER_ERROR);
        return;
    }

    try (CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(metsDocumentUri))) {
        if (httpResponse.getStatusLine().getStatusCode() != SC_OK) {
            resp.sendError(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
            return;
        }
        Document metsDocument = new SAXBuilder().build(httpResponse.getEntity().getContent());

        EpicurBuilder epicurBuilder = new EpicurBuilder().encodePid(transferUrlPidencode)
                .agentNameSubstitutions(agentNameSubstitutions).frontpageUrlPattern(frontpageUrlPattern)
                .mets(metsDocument).transferUrlPattern(transferUrlPattern).updateStatus(UpdateStatus.urn_new);
        Epicur epicur = epicurBuilder.build();

        StringWriter stringWriter = new StringWriter();

        Marshaller marshaller = marshallerPool.borrowObject();
        marshaller.marshal(epicur, stringWriter);
        marshallerPool.returnObject(marshaller);

        resp.setCharacterEncoding(Charset.defaultCharset().name());
        resp.setContentType("application/xml");
        resp.getOutputStream().print(stringWriter.toString());

    } catch (Exception e) {
        log.error("Error while writing XML content: " + e.getMessage());
        if (!resp.isCommitted()) {
            resp.sendError(SC_INTERNAL_SERVER_ERROR);
        } else {
            log.warn("Response already committed. Cannot send error code.");
        }
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response,
        Resource resource) throws IOException {
    try {//from  w  w w  . j  av a  2  s . c o  m
        if (!request.getMethod().equals(HttpMethod.HEAD.asString())) {

            String ifms = request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
            if (ifms != null) {

                long ifmsl = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
                if (ifmsl != -1) {
                    if (resource.lastModified() / 1000 <= ifmsl / 1000) {
                        response.reset();
                        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        response.flushBuffer();
                        return false;
                    }
                }
            }

            // Parse the if[un]modified dates and compare to resource
            long date = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString());

            if (date != -1) {
                if (resource.lastModified() / 1000 > date / 1000) {
                    response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                    return false;
                }
            }
        }
    } catch (IllegalArgumentException iae) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
            return false;
        }
        throw iae;
    }
    return true;
}

From source file:org.josso.wls10.agent.WLSAgentServletFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;

    if (log.isDebugEnabled())
        log.debug("Processing : " + hreq.getContextPath());

    try {//from   ww  w .ja v  a2s  .  c  om
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();

        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        if (!_agent.isPartnerApp(request.getServerName(), contextPath)) {
            filterChain.doFilter(hreq, hres);
            log.warn("JOSSO WLS 10 Filter is running on a non-JOSSO Partner application!");

            return;
        }

        String nodeId = hreq.getParameter("josso_node");
        if (nodeId != null) {
            if (log.isDebugEnabled())
                log.debug("Storing JOSSO Node id : " + nodeId);
            _agent.setAttribute(hreq, hres, "JOSSO_NODE", nodeId);
        } else {
            nodeId = _agent.getAttribute(hreq, "JOSSO_NODE");
            if (log.isDebugEnabled())
                log.debug("Found JOSSO Node id : " + nodeId);
        }

        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(request.getServerName(), contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        HttpSession session = hreq.getSession(true);

        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJossoUserLoginUri())) {
                saveLoginBackToURL(hreq, hres, session, true);
            } else {
                saveLoginBackToURL(hreq, hres, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (log.isDebugEnabled())
                log.debug("Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoLogoutUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (log.isDebugEnabled())
                log.debug("Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
            hres.addCookie(ssoCookie);

            // logout user (remove data from the session and webserver)
            // (The LoginModule.logout method is never called 
            // for the WebLogic Authentication providers or custom Authentication providers. 
            // This is simply because once the principals are created and placed into a subject, 
            // the WebLogic Security Framework no longer controls the lifecycle of the subject)
            _agent.prepareNonCacheResponse(hres);
            ServletAuthentication.logout(hreq);

            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));
            return;

        }

        // ------------------------------------------------------------------
        // Check for the single sign on cookie
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking for SSO cookie");
        Cookie cookie = null;
        Cookie cookies[] = hreq.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            if (org.josso.gateway.Constants.JOSSO_SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
                cookie = cookies[i];
                break;
            }
        }

        String jossoSessionId = (cookie == null) ? null : cookie.getValue();
        if (log.isDebugEnabled())
            log.debug("Session is: " + session);
        LocalSession localSession = new GenericServletLocalSession(session);

        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (log.isDebugEnabled()) {
            log.debug("Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJossoAuthenticationUri())) {

            if (log.isDebugEnabled())
                log.debug("josso_authentication received for uri '" + hreq.getRequestURI() + "'");

            SSOAgentRequest customAuthRequest = doMakeSSOAgentRequest(cfg.getId(),
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, nodeId,
                    hreq, hres);
            _agent.processRequest(customAuthRequest);

            return;
        }

        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (log.isDebugEnabled())
                    log.debug(_agent.getJossoSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(hreq);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq, hres)) {

                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can go back to it later ...
                    saveRequestURL(hreq, hres);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (log.isDebugEnabled())
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (log.isDebugEnabled())
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }
            }

            if (log.isDebugEnabled())
                log.debug("SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            filterChain.doFilter(hreq, hres);
            return;
        }

        // This URI should be protected by SSO, go on ...

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Executing agent...");

        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJossoSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (log.isDebugEnabled())
                log.debug("josso_security_check received for uri '" + hreq.getRequestURI() + "' assertion id '"
                        + hreq.getParameter("josso_assertion_id"));

            String assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            SSOAgentRequest relayRequest;

            if (log.isDebugEnabled())
                log.debug("Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_RELAY, null, localSession,
                    assertionId, nodeId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error(
                        "Outbound relaying failed for assertion id [" + assertionId + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException(
                        "Outbound relaying failed. No Principal found. Verify your SSO Agent Configuration!");
            }

            if (log.isDebugEnabled())
                log.debug("Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (log.isDebugEnabled())
                log.debug("Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId, hreq.isSecure());
            hres.addCookie(cookie);

            //Redirect user to the saved splash resource (in case of auth request) or to request URI otherwise
            String requestURI = getSavedSplashResource(hreq);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(hreq);
                if (requestURI == null) {
                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJossoSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (log.isDebugEnabled())
                        log.debug("No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(hreq, hres);
            _agent.clearAutomaticLoginReferer(hreq, hres);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (log.isDebugEnabled())
                    log.debug("Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }

            return;
        }

        SSOAgentRequest r;
        log.debug("Creating Security Context for Session [" + session + "]");
        r = doMakeSSOAgentRequest(cfg.getId(), SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                jossoSessionId, localSession, null, nodeId, hreq, hres);

        SingleSignOnEntry entry = _agent.processRequest(r);

        if (log.isDebugEnabled())
            log.debug("Executed agent.");

        // Get session map for this servlet context.
        Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
        if (sessionMap.get(localSession.getWrapped()) == null) {
            // the local session is new so, make the valve listen for its events so that it can
            // map them to local session events.
            // TODO : Not supported ... session.addSessionListener(this);
            sessionMap.put(session, localSession);
        }

        // ------------------------------------------------------------------
        // Has a valid user already been authenticated?
        // ------------------------------------------------------------------
        if (log.isDebugEnabled())
            log.debug("Process request for '" + hreq.getRequestURI() + "'");

        if (entry != null) {
            if (log.isDebugEnabled())
                log.debug("Principal '" + entry.principal + "' has already been authenticated");
            // TODO : Not supported
            // (request).setAuthType(entry.authType);
            // (request).setUserPrincipal(entry.principal);
        } else {
            log.info("No Valid SSO Session, attempt an optional login?");
            // This is a standard anonymous request!

            if (cookie != null) {
                // cookie is not valid
                cookie = _agent.newJossoCookie(hreq.getContextPath(), "-", hreq.isSecure());
                hres.addCookie(cookie);
            }

            if (cookie != null
                    || (getSavedRequestURL(hreq) == null && _agent.isAutomaticLoginRequired(hreq, hres))) {

                if (log.isDebugEnabled())
                    log.debug("SSO Session is not valid, attempting automatic login");

                // Save current request, so we can go back to it later ...
                saveRequestURL(hreq, hres);
                String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                if (log.isDebugEnabled())
                    log.debug("Redirecting to login url '" + loginUrl + "'");

                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                return;
            } else {
                if (log.isDebugEnabled())
                    log.debug("SSO cookie is not present, but login optional process is not required");
            }

        }

        // propagate the login and logout URLs to
        // partner applications.
        hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
        hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
        hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

        // ------------------------------------------------------------------
        // Invoke the next Valve in our pipeline
        // ------------------------------------------------------------------
        filterChain.doFilter(hreq, hres);
    } finally {
        if (log.isDebugEnabled())
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:org.josso.servlet.agent.JossoFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) request;

    HttpServletResponse hres = (HttpServletResponse) response;
    debug = 1;/*from   w w  w  .jav  a 2  s .c  o  m*/
    if (debug == 1)
        log.debug("Processing : " + hreq.getContextPath());

    try {
        // ------------------------------------------------------------------
        // Check with the agent if this context should be processed.
        // ------------------------------------------------------------------
        String contextPath = hreq.getContextPath();
        String vhost = hreq.getServerName();
        //_agent.setCatalinaContainer(container);
        // In catalina, the empty context is considered the root context
        if ("".equals(contextPath))
            contextPath = "/";

        // T1 si l'appli n'est pas partenaire alors pas de SSO on continue
        if (!_agent.isPartnerApp(vhost, contextPath)) {
            filterChain.doFilter(hreq, hres);
            logg("T1 Context is not a josso partner app : " + hreq.getContextPath());
            hres.sendError(hres.SC_UNAUTHORIZED, "vrifier config agent ajouter le contexte");
            return;
        } else {
            logg("T1 Context IS a josso partner app =" + hreq.getContextPath());
        }

        //T2
        // ------------------------------------------------------------------
        // Check some basic HTTP handling
        // ------------------------------------------------------------------
        // P3P Header for IE 6+ compatibility when embedding JOSSO in a IFRAME
        SSOPartnerAppConfig cfg = _agent.getPartnerAppConfig(vhost, contextPath);
        if (cfg.isSendP3PHeader() && !hres.isCommitted()) {
            hres.setHeader("P3P", cfg.getP3PHeaderValue());
        }

        //T9
        // ------------------------------------------------------------------
        // Check if this URI is subject to SSO protection
        // ------------------------------------------------------------------
        if (_agent.isResourceIgnored(cfg, hreq)) {
            logg("T9 ressource non ssois (accs libre)");
            filterChain.doFilter(hreq, hres);
            return;
        }

        // Get our session ...
        HttpSession session = hreq.getSession(true);

        testCookieSession(hreq);
        //TA1 pas de cookie et on trouve la page de login attendue dans la dclaration du contexte agent
        logg("TA1 uri=" + hreq.getRequestURI() + " se termine par " + cfg.getLoginPage() + " rep="
                + hreq.getRequestURI().endsWith(cfg.getLoginPage()) + " test cookie="
                + testCookie2Session(hreq, session.getId()));
        if (!testCookie2Session(hreq, session.getId()) && hreq.getRequestURI().endsWith(cfg.getLoginPage())) {
            logg("TA1 on demande l'authentification locale on switche vers Josso");
            Cookie gato = newJossoCookie2(hreq.getContextPath(), session.getId(), COOKIE_LOGIN);
            hres.addCookie(gato);
            String loginUrl = _agent.buildLoginUrl(hreq);
            hres.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            //response.setHeader("Location", jeVeux);
            hres.sendRedirect(loginUrl);
            return;
        }
        //T3 on revient aprs authentification russie et pour finalisation
        if (_agent.isSSOIDloged(jossoSessionId)) {
            iBoucle++;
            logg("T3 Info retour authentifi pour " + jossoSessionId + " faire retour vers " + theOriginal);
            SSOAgentRequest r = doMakeSSOAgentRequest(SSOAgentRequest.ACTION_ESTABLISH_SECURITY_CONTEXT,
                    jossoSessionId, localSession, null, hreq, hres);
            SingleSignOnEntry entry = _agent.processRequest(r);

            if (debug == 1)
                log.debug("Executed agent.");

            // Get session map for this servlet context.
            Map sessionMap = (Map) hreq.getSession().getServletContext().getAttribute(KEY_SESSION_MAP);
            if (sessionMap.get(localSession.getWrapped()) == null) {
                // the local session is new so, make the valve listen for its events so that it can
                // map them to local session events.
                // Not supported : session.addSessionListener(this);
                sessionMap.put(session, localSession);
            }

            // ------------------------------------------------------------------
            // Has a valid user already been authenticated?
            // ------------------------------------------------------------------
            if (debug == 1)
                log.debug("Process request for '" + hreq.getRequestURI() + "'");

            if (entry != null) {
                if (debug == 1)
                    log.debug("Principal '" + entry.principal + "' has already been authenticated");
                // TODO : Not supported
                // (request).setAuthType(entry.authType);
                // (request).setUserPrincipal(entry.principal);
            } else {
                log.info("No Valid SSO Session, attempt an optional login?");
                // This is a standard anonymous request!

                if (cookie != null) {
                    // cookie is not valid
                    cookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
                    hres.addCookie(cookie);
                }

                if (cookie != null
                        || (getSavedRequestURL(session) == null && _agent.isAutomaticLoginRequired(hreq))) {

                    if (debug == 1)
                        log.debug("SSO Session is not valid, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log.debug("Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (debug == 1)
                        log.debug("SSO cookie is not present, but login optional process is not required");
                }

            }
            try {
                logg("Avant sur webProgrammaticLogin -------------" + iBoucle);

                if (!WebProgrammaticLogin.login(jossoSessionId, assertionId, "jossoRealm", hreq, hres)) {
                    logg("Erreur sur webProgrammaticLogin");
                } else {
                    logg("Russite sur webProgrammaticLogin");
                }
                logg("Aprs sur webProgrammaticLogin-------------" + iBoucle);
            } catch (Exception err) {
                logg("SSOAgentValve Erreur2 finalisation contexte securit", err);
                throw new ServletException(err);
            }

            // propagate the login and logout URLs to
            // partner applications.
            hreq.setAttribute("org.josso.agent.gateway-login-url", _agent.getGatewayLoginUrl());
            hreq.setAttribute("org.josso.agent.gateway-logout-url", _agent.getGatewayLogoutUrl());
            hreq.setAttribute("org.josso.agent.ssoSessionid", jossoSessionId);

            // ------------------------------------------------------------------
            // Invoke the next Valve in our pipeline
            // ------------------------------------------------------------------
            filterChain.doFilter(hreq, hres);
        }

        //T4
        // ------------------------------------------------------------------
        // Check if the partner application required the login form
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T4 Checking if its a josso_login_request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLoginUri())
                || hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {

            if (debug == 1)
                log.debug("T4 josso_login_request received for uri '" + hreq.getRequestURI() + "'");

            //save referer url in case the user clicked on Login from some public resource (page)
            //so agent can redirect the user back to that page after successful login
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOUserLoginUri())) {
                saveLoginBackToURL(hreq, session, true);
            } else {
                saveLoginBackToURL(hreq, session, false);
            }

            String loginUrl = _agent.buildLoginUrl(hreq);

            if (debug == 1)
                log.debug("T4 Redirecting to login url '" + loginUrl + "'");

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(loginUrl));

            return;

        }

        //T5
        // ------------------------------------------------------------------
        // Check if the partner application required a logout
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T5 Checking if its a josso_logout request for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOLogoutUri())) {

            if (debug == 1)
                log.debug("T5 josso_logout request received for uri '" + hreq.getRequestURI() + "'");

            String logoutUrl = _agent.buildLogoutUrl(hreq, cfg);

            if (debug == 1)
                log.debug("T5 Redirecting to logout url '" + logoutUrl + "'");

            // Clear previous COOKIE ...
            Cookie ssoCookie = _agent.newJossoCookie(hreq.getContextPath(), "-");
            hres.addCookie(ssoCookie);

            // invalidate session (unbind josso security context)
            session.invalidate();

            //set non cache headers
            _agent.prepareNonCacheResponse(hres);
            hres.sendRedirect(hres.encodeRedirectURL(logoutUrl));

            return;

        }

        //T6
        testCookieSession(hreq);
        //T7
        // ------------------------------------------------------------------
        // Check if the partner application submitted custom login form
        // ------------------------------------------------------------------

        if (debug == 1) {
            log.debug("T7 Checking if its a josso_authentication for '" + hreq.getRequestURI() + "'");
        }
        if (hreq.getRequestURI().endsWith(_agent.getJOSSOAuthenticationUri())) {

            if (debug == 1) {
                log.debug("T7 josso_authentication received for uri '" + hreq.getRequestURI() + "'");
            }

            GenericServletSSOAgentRequest customAuthRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(
                    SSOAgentRequest.ACTION_CUSTOM_AUTHENTICATION, jossoSessionId, localSession, null, hreq,
                    hres);

            _agent.processRequest(customAuthRequest);

            return;
        }
        //T8
        // si pas de cookie de session SSO
        if (cookie == null || cookie.getValue().equals("-")) {

            // ------------------------------------------------------------------
            // Trigger LOGIN OPTIONAL if required
            // ------------------------------------------------------------------

            if (debug == 1)
                log.debug("T8 SSO cookie is not present, verifying optional login process ");

            // We have no cookie, remember me is enabled and a security check without assertion was received ...
            // This means that the user could not be identified ... go back to the original resource
            if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") == null) {

                if (debug == 1)
                    log.debug("T8-1 " + _agent.getJOSSOSecurityCheckUri()
                            + " received without assertion.  Login Optional Process failed");

                String requestURI = getSavedRequestURL(session);
                _agent.prepareNonCacheResponse(hres);
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
                return;

            }

            // This is a standard anonymous request!
            if (!hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())) {

                if (!_agent.isResourceIgnored(cfg, hreq) && _agent.isAutomaticLoginRequired(hreq)) {

                    if (debug == 1)
                        log.debug("T8-2 SSO cookie is not present, attempting automatic login");

                    // Save current request, so we can co back to it later ...
                    saveRequestURL(hreq, session);
                    String loginUrl = _agent.buildLoginOptionalUrl(hreq);

                    if (debug == 1)
                        log.debug("T8-2 Redirecting to login url '" + loginUrl + "'");

                    //set non cache headers
                    _agent.prepareNonCacheResponse(hres);
                    hres.sendRedirect(hres.encodeRedirectURL(loginUrl));
                    return;
                } else {
                    if (debug == 1)
                        log.debug("T8-2 SSO cookie is not present, but login optional process is not required");
                }
            }

            if (debug == 1)
                log.debug("T8-3 SSO cookie is not present, checking for outbound relaying");

            if (!(hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                    && hreq.getParameter("josso_assertion_id") != null)) {
                log.debug("T8-3 SSO cookie not present and relaying was not requested, skipping");
                filterChain.doFilter(hreq, hres);
                return;
            }

        }

        // This URI should be protected by SSO, go on ...
        if (debug == 1)
            log.debug("Session is: " + session);

        // ------------------------------------------------------------------
        // Invoke the SSO Agent
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("Executing agent...");
        //T10  /josso_security_check
        // ------------------------------------------------------------------
        // Check if a user has been authenitcated and should be checked by the agent.
        // ------------------------------------------------------------------
        if (debug == 1)
            log.debug("T10 Checking if its a josso_security_check for '" + hreq.getRequestURI() + "'");

        if (hreq.getRequestURI().endsWith(_agent.getJOSSOSecurityCheckUri())
                && hreq.getParameter("josso_assertion_id") != null) {

            if (debug == 1)
                log.debug("T10 josso_security_check received for uri '" + hreq.getRequestURI()
                        + "' assertion id '" + hreq.getParameter("josso_assertion_id"));

            assertionId = hreq.getParameter(Constants.JOSSO_ASSERTION_ID_PARAMETER);

            GenericServletSSOAgentRequest relayRequest;

            if (debug == 1)
                log.debug("T10 Outbound relaying requested for assertion id [" + assertionId + "]");

            relayRequest = (GenericServletSSOAgentRequest) doMakeSSOAgentRequest(SSOAgentRequest.ACTION_RELAY,
                    null, localSession, assertionId, hreq, hres);

            SingleSignOnEntry entry = _agent.processRequest(relayRequest);
            if (entry == null) {
                // This is wrong! We should have an entry here!
                log.error("T10-1 Outbound relaying failed for assertion id [" + assertionId
                        + "], no Principal found.");
                // Throw an exception and let the container send the INERNAL SERVER ERROR
                throw new ServletException("No Principal found. Verify your SSO Agent Configuration!");
            }

            if (debug == 1)
                log.debug("T10-2 Outbound relaying succesfull for assertion id [" + assertionId + "]");

            if (debug == 1)
                log.debug("T10-2 Assertion id [" + assertionId + "] mapped to SSO session id [" + entry.ssoId
                        + "]");

            // The cookie is valid to for the partner application only ... in the future each partner app may
            // store a different auth. token (SSO SESSION) value
            cookie = _agent.newJossoCookie(hreq.getContextPath(), entry.ssoId);
            hres.addCookie(cookie);

            // Redirect the user to the original request URI (which will cause
            // the original request to be restored)
            String requestURI = getSavedSplashResource(session);
            if (requestURI == null) {
                requestURI = getSavedRequestURL(session);
                if (requestURI == null) {

                    if (cfg.getDefaultResource() != null) {
                        requestURI = cfg.getDefaultResource();
                    } else {
                        // If no saved request is found, redirect to the partner app root :
                        requestURI = hreq.getRequestURI().substring(0,
                                (hreq.getRequestURI().length() - _agent.getJOSSOSecurityCheckUri().length()));
                    }

                    // If we're behind a reverse proxy, we have to alter the URL ... this was not necessary on tomcat 5.0 ?!
                    String singlePointOfAccess = _agent.getSinglePointOfAccess();
                    if (singlePointOfAccess != null) {
                        requestURI = singlePointOfAccess + requestURI;
                    } else {
                        String reverseProxyHost = hreq
                                .getHeader(org.josso.gateway.Constants.JOSSO_REVERSE_PROXY_HEADER);
                        if (reverseProxyHost != null) {
                            requestURI = reverseProxyHost + requestURI;
                        }
                    }

                    if (debug == 1)
                        log.debug("T10 No saved request found, using : '" + requestURI + "'");
                }
            }

            clearSavedRequestURLs(session);
            _agent.clearAutomaticLoginReferer(hreq);
            _agent.prepareNonCacheResponse(hres);

            // Check if we have a post login resource :
            String postAuthURI = cfg.getPostAuthenticationResource();
            if (postAuthURI != null) {
                String postAuthURL = _agent.buildPostAuthUrl(hres, requestURI, postAuthURI);
                if (debug == 1)
                    log.debug("T10 Redirecting to post-auth-resource '" + postAuthURL + "'");
                hres.sendRedirect(postAuthURL);
            } else {
                if (debug == 1)
                    log.debug("T10 Redirecting to original '" + requestURI + "'");
                hres.sendRedirect(hres.encodeRedirectURL(requestURI));
            }
            _agent.addEntrySSOIDsuccessed(entry.ssoId, entry.getPrincipal().getName());
            return;
        }

    } finally {
        if (debug == 1)
            log.debug("Processed : " + hreq.getContextPath());
    }
}

From source file:org.vast.ows.server.OWSServlet.java

/**
 * Parse and process all types of requests
 * @param req/*from  w  w  w. j  a  va 2s.  c  o m*/
 * @param resp
 * @param post
 */
protected void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean post) {
    //  get actual request URL
    String requestURL = req.getRequestURL().toString();
    OWSRequest request = null;

    try {
        // parse request            
        try {
            if (post) {
                InputStream xmlRequest = new PostRequestFilter(new BufferedInputStream(req.getInputStream()));
                DOMHelper dom = new DOMHelper(xmlRequest, false);
                request = owsUtils.readXMLQuery(dom, dom.getBaseElement());
            } else {
                String queryString = req.getQueryString();
                if (queryString == null)
                    throw new IllegalArgumentException();
                request = owsUtils.readURLQuery(queryString);
            }
        } catch (IllegalArgumentException e) {
            try {
                resp.sendError(400, invalidKVPRequestMsg);
            } catch (IOException e1) {
                log.error(internalErrorMsg, e1);
            }
        } catch (DOMHelperException e) {
            try {
                resp.sendError(400, invalidXMLRequestMsg);
            } catch (IOException e1) {
                log.error(internalErrorMsg, e1);
            }
        }

        // write response
        // set default mime type 
        resp.setContentType(XML_MIME_TYPE);

        // keep http objects in request
        request.setHttpRequest(req);
        request.setHttpResponse(resp);
        request.setPostServer(requestURL);

        // if capabilities request, deal with it in a generic manner
        if (request instanceof GetCapabilitiesRequest)
            this.handleRequest(request);

        // else let specific code handle the request
        else
            this.handleRequest(request);
    } catch (OWSException e) {
        try {
            resp.setContentType(XML_MIME_TYPE);
            String version = (request != null) ? request.getVersion() : getDefaultVersion();
            owsUtils.writeXMLException(new BufferedOutputStream(resp.getOutputStream()), getServiceType(),
                    version, e);
            log.debug(e.getMessage(), e);
        } catch (IOException e1) {
            log.error(internalErrorMsg, e1);
        }
    } catch (WriterException e) {
        log.debug(internalErrorMsg, e);
    } catch (Exception e) {
        try {
            if (!resp.isCommitted())
                resp.sendError(500, internalErrorMsg);
            log.error(internalErrorMsg, e);
        } catch (IOException e1) {
        }
    } finally {
        try {
            resp.getOutputStream().flush();
        } catch (IOException e) {
        }
    }
}

From source file:com.alfaariss.oa.sso.web.profile.ssoquery.SSOQueryProfile.java

/**
 * @see com.alfaariss.oa.api.IService#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from w w  w  .ja  v  a  2  s .  c  om
public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException {
    try {
        if (!_bEnabled) {
            _logger.debug("Component is disabled");
            throw new UserException(UserEvent.INTERNAL_ERROR);
        }

        _logger.debug("Performing 'sso query' request sent from IP: " + servletRequest.getRemoteAddr());

        String responseUrl = servletRequest.getParameter(PARAM_RESPONSE_URL);
        if (responseUrl == null) {
            _logger.debug("No parameter '" + PARAM_RESPONSE_URL + "' available in request");
            throw new UserException(UserEvent.REQUEST_INVALID);
        }

        if (_whitelist != null) {
            try {
                URL urlResponse = new URL(responseUrl);

                if (!_whitelist.isWhitelisted(urlResponse.getHost())) {
                    _logger.debug("Hostname isn't whitelisted: " + urlResponse.getHost());
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
            } catch (MalformedURLException e) {
                StringBuffer sbError = new StringBuffer("Invalid parameter '");
                sbError.append(PARAM_RESPONSE_URL);
                sbError.append("' available in request: ");
                sbError.append(responseUrl);
                _logger.debug(sbError.toString());

                throw new UserException(UserEvent.REQUEST_INVALID);
            }
        }

        String sResult = "false";
        String sTGTCookie = _cookieTool.getCookieValue(WebSSOServlet.TGT_COOKIE_NAME, servletRequest);
        if (sTGTCookie != null) {
            ITGT tgt = _tgtFactory.retrieve(sTGTCookie);
            if (tgt != null && !tgt.isExpired())
                sResult = "true";
        }

        StringBuffer sbRedirect = new StringBuffer(responseUrl);
        if (responseUrl.contains("?"))
            sbRedirect.append("&");
        else
            sbRedirect.append("?");

        sbRedirect.append(PARAM_RESULT);
        sbRedirect.append("=");
        sbRedirect.append(sResult);

        _eventLogger.info(new RequestorEventLogItem(null, sTGTCookie, null, RequestorEvent.QUERY_SUCCESSFUL,
                null, servletRequest.getRemoteAddr(), null, this, sResult));

        _logger.debug("Redirecting user to: " + sbRedirect.toString());
        servletResponse.sendRedirect(sbRedirect.toString());
    } catch (UserException e) {
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.debug("Could not respond", e1);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (Exception e) {
        _logger.fatal("Internal error during sso request", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.tightblog.rendering.processors.MediaFileProcessor.java

@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD })
void getMediaFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    WeblogRequest incomingRequest = WeblogRequest.create(request);

    Weblog weblog = weblogRepository.findByHandleAndVisibleTrue(incomingRequest.getWeblogHandle());
    if (weblog == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w  ww. j a  va  2s  .  co  m*/
    } else {
        incomingRequest.setWeblog(weblog);
    }

    MediaFile mediaFile = null;
    // path info here is the resourceId
    String pathInfo = incomingRequest.getExtraPathInfo();
    if (StringUtils.isNotBlank(pathInfo)) {
        mediaFile = mediaManager.getMediaFileWithContent(pathInfo);
    }

    if (mediaFile == null) {
        log.info("Could not obtain media file for resource path: ", request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    weblogMediaCache.incrementIncomingRequests();

    // DB stores last modified in millis, browser if-modified-since in seconds, so need to truncate millis from the former.
    long inDb = mediaFile.getLastUpdated().truncatedTo(ChronoUnit.SECONDS).toEpochMilli();
    long inBrowser = getBrowserCacheExpireDate(request);

    if (inDb <= inBrowser) {
        weblogMediaCache.incrementRequestsHandledBy304();
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    boolean useThumbnail = false;
    if (mediaFile.isImageFile() && "true".equals(request.getParameter("tn"))) {
        useThumbnail = true;
    }

    File desiredFile = useThumbnail ? mediaFile.getThumbnail() : mediaFile.getContent();
    if (desiredFile == null) {
        log.info("Could not obtain {} file content for resource path: ", useThumbnail ? "thumbnail" : "",
                request.getRequestURL());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try (InputStream resourceStream = new FileInputStream(desiredFile);
            OutputStream out = response.getOutputStream()) {

        byte[] buf = new byte[Utilities.EIGHT_KB_IN_BYTES];
        int length;
        while ((length = resourceStream.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
        response.setContentType(useThumbnail ? MediaFile.THUMBNAIL_CONTENT_TYPE : mediaFile.getContentType());
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Last-Modified", mediaFile.getLastUpdated().toEpochMilli());
    } catch (IOException ex) {
        log.error("Error obtaining media file {}", desiredFile.getAbsolutePath(), ex);
        if (!response.isCommitted()) {
            response.reset();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

From source file:org.nema.medical.mint.server.controller.ChangeLogController.java

@RequestMapping("/studies/{uuid}/changelog/{seq}")
public void studiesChangeLog(@PathVariable("uuid") final String uuid, @PathVariable("seq") final String seq,
        final HttpServletRequest req, final HttpServletResponse res) throws IOException {

    final Utils.StudyStatus studyStatus = Utils.validateStudyStatus(studiesRoot, uuid, res, studyDAO);
    if (studyStatus != Utils.StudyStatus.OK) {
        return;//from  w  w  w . ja  v  a2s . c o m
    }

    /*
     * The path variable 'seq' when '0.gpb' is on the end of the URL seems
     * to be only '0' for some reason. I'm not sure what the weirdness is
     * with '.' in the URL. The following call should return the expected
     * sequence (i.e., '0.gpb').
     */
    String tmp = req.getAttribute("org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping")
            .toString();
    if (StringUtils.isBlank(tmp)) {
        tmp = seq;
    }

    if (StringUtils.isBlank(tmp)) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Empty");
        return;
    }

    final Long sequence;
    String ext = null;
    final int extPoint = tmp.indexOf('.');
    if (extPoint > -1) {
        try {
            sequence = Long.valueOf(tmp.substring(0, extPoint));
            ext = tmp.substring(extPoint + 1);
        } catch (final NumberFormatException e) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: NaN");
            return;
        }
    } else {
        try {
            sequence = Long.valueOf(tmp);
        } catch (final NumberFormatException e) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: NaN");
            return;
        }
    }

    if (StringUtils.isBlank(ext)) {
        ext = "xml";
    }

    if (sequence < 0) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Negative");
        return;
    }
    if (sequence >= Integer.MAX_VALUE) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid sequence requested: Too large");
        return;
    }

    res.setBufferSize(fileResponseBufferSize);
    try {
        final File file = new File(studiesRoot, uuid + "/changelog/" + sequence + "/metadata." + ext);
        if (file.exists() && file.canRead()) {
            final OutputStream out = res.getOutputStream();
            res.setContentLength((int) file.length());
            res.setContentType("text/xml");
            Utils.streamFile(file, out, fileStreamBufferSize);
        } else {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid study requested: Not found");
        }
    } catch (final IOException e) {
        if (!res.isCommitted()) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot provide study change log: File Read Failure");
        }
    }
}

From source file:org.jumpmind.symmetric.web.SymmetricServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServerSymmetricEngine engine = findEngine(req);
    MDC.put("engineName", engine != null ? engine.getEngineName() : "?");
    if (engine == null) {
        boolean nodesBeingCreated = ServletUtils.getSymmetricEngineHolder(getServletContext())
                .areEnginesStarting();/*from   w  w w.ja v  a2 s  .  c o m*/
        if (nodesBeingCreated) {
            log.info(
                    "The client node request is being rejected because the server node does not exist yet.  There are nodes being initialized.  It might be that the node is not ready or that the database is unavailable.  Please be patient.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
        } else {
            log.error(
                    "The client node request is being rejected because the server node does not exist.  Please check that the engine.name exists in the url.  It should be of the pattern http://host:port/sync/{engine.name}/{action}.  If it does not, then check the sync.url of this node or the registration.url of the client making the request.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
        }
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);

    } else if (engine.isStarted()) {
        IUriHandler handler = findMatchingHandler(engine, req);
        if (handler != null) {
            List<IInterceptor> beforeInterceptors = handler.getInterceptors();
            List<IInterceptor> afterInterceptors = null;
            try {
                if (beforeInterceptors != null) {
                    afterInterceptors = new ArrayList<IInterceptor>(beforeInterceptors.size());
                    for (IInterceptor interceptor : beforeInterceptors) {
                        if (interceptor.before(req, res)) {
                            afterInterceptors.add(interceptor);
                        } else {
                            return;
                        }
                    }
                }
                handler.handle(req, res);
            } catch (Exception e) {
                logException(req, e, !(e instanceof IOException && StringUtils.isNotBlank(e.getMessage())));
                if (!res.isCommitted()) {
                    ServletUtils.sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            } finally {
                if (afterInterceptors != null) {
                    for (IInterceptor interceptor : afterInterceptors) {
                        interceptor.after(req, res);
                    }
                }
            }
        } else {
            log.error(
                    "The request path of the url is not supported.  The request was {} from the host {} with an ip address of {}.  The query string was: {}",
                    new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(),
                            req.getRemoteAddr(), req.getQueryString() });
            ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST);
        }
    } else if (engine.isStarting()) {
        log.info(
                "The client node request is being rejected because the server node is currently starting.  Please be patient.  The request was {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    } else if (!engine.isStarted() && !engine.isConfigured()) {
        log.info(
                "The client node request is being rejected because the server node was not started because it is not configured properly. The request {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    } else {
        log.debug(
                "The client node request is being rejected because the server node is not started. The request {} from the host {} with an ip address of {} will not be processed.  The query string was: {}",
                new Object[] { ServletUtils.normalizeRequestUri(req), req.getRemoteHost(), req.getRemoteAddr(),
                        req.getQueryString() });
        ServletUtils.sendError(res, WebConstants.SC_SERVICE_UNAVAILABLE);
    }

}