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:net.yacy.http.servlets.YaCyDefaultServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo;//from w  ww.  ja v  a  2  s.c o m
    Enumeration<String> reqRanges = null;
    boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null;
    if (included) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        if (pathInfo == null) {
            pathInfo = request.getPathInfo();
        }
    } else {
        pathInfo = request.getPathInfo();

        // Is this a Range request?
        reqRanges = request.getHeaders(HeaderFramework.RANGE);
        if (!hasDefinedRange(reqRanges)) {
            reqRanges = null;
        }
    }

    String pathInContext = pathInfo == null ? "/" : pathInfo; // this is the path of the resource in _resourceBase (= path within htroot respective htDocs)
    boolean endsWithSlash = pathInContext.endsWith(URIUtil.SLASH);

    // Find the resource 
    Resource resource = null;

    try {

        // Look for a class resource
        boolean hasClass = false;
        if (reqRanges == null && !endsWithSlash) {
            final int p = pathInContext.lastIndexOf('.');
            if (p >= 0) {
                String pathofClass = pathInContext.substring(0, p) + ".class";
                Resource classresource = _resourceBase.addPath(pathofClass);
                // Does a class resource exist?
                if (classresource != null && classresource.exists() && !classresource.isDirectory()) {
                    hasClass = true;
                }
            }
        }

        // find resource
        resource = getResource(pathInContext);

        if (!hasClass && (resource == null || !resource.exists()) && !pathInContext.contains("..")) {
            // try to get this in the alternative htDocsPath
            resource = Resource.newResource(new File(_htDocsPath, pathInContext));
        }

        if (ConcurrentLog.isFine("FILEHANDLER")) {
            ConcurrentLog.fine("FILEHANDLER",
                    "YaCyDefaultServlet: uri=" + request.getRequestURI() + " resource=" + resource);
        }

        // Handle resource
        if (!hasClass && (resource == null || !resource.exists())) {
            if (included) {
                throw new FileNotFoundException("!" + pathInContext);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (!resource.isDirectory()) {
            if (endsWithSlash && pathInContext.length() > 1) {
                String q = request.getQueryString();
                pathInContext = pathInContext.substring(0, pathInContext.length() - 1);
                if (q != null && q.length() != 0) {
                    pathInContext += "?" + q;
                }
                response.sendRedirect(response
                        .encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(), pathInContext)));
            } else {
                if (hasClass) { // this is a YaCy servlet, handle the template
                    handleTemplate(pathInfo, request, response);
                } else {
                    if (included || passConditionalHeaders(request, response, resource)) {
                        sendData(request, response, included, resource, reqRanges);
                    }
                }
            }
        } else { // resource is directory
            String welcome;

            if (!endsWithSlash) {
                StringBuffer buf = request.getRequestURL();
                synchronized (buf) {
                    int param = buf.lastIndexOf(";");
                    if (param < 0) {
                        buf.append('/');
                    } else {
                        buf.insert(param, '/');
                    }
                    String q = request.getQueryString();
                    if (q != null && q.length() != 0) {
                        buf.append('?');
                        buf.append(q);
                    }
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(buf.toString()));
                }
            } // else look for a welcome file
            else if (null != (welcome = getWelcomeFile(pathInContext))) {
                ConcurrentLog.fine("FILEHANDLER", "welcome={}" + welcome);

                // Forward to the index
                RequestDispatcher dispatcher = request.getRequestDispatcher(welcome);
                if (dispatcher != null) {
                    if (included) {
                        dispatcher.include(request, response);
                    } else {
                        dispatcher.forward(request, response);
                    }
                }
            } else {
                if (included || passConditionalHeaders(request, response, resource)) {
                    sendDirectory(request, response, resource, pathInContext);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        ConcurrentLog.logException(e);
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } finally {
        if (resource != null) {
            resource.close();
        }
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.re.ResponseEndpoint.java

private void processResponse(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context) throws OAException {
    String sRequestorId = null;// ww  w. ja  va2  s  .  c om
    try {
        sRequestorId = context.getInboundMessageIssuer();
        if (sRequestorId != null)
            _logger.debug("issuer: " + sRequestorId);

        if (_idpStorageManager.getIDP(sRequestorId) == null) {
            _logger.debug("Processing of SAML2 message failed because issuer is not known: " + sRequestorId);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        SignableSAMLObject obj = context.getInboundSAMLMessage();
        if (obj == null) {
            _logger.debug("No SAML message object in request from issuer: " + sRequestorId);
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        if (_logger.isDebugEnabled())
            logXML(obj);

        //DD: Session ID is extracted from InResponseTo. If null, relaystate or target are used for Unsolicited Response.
        String sSessionID = null;
        String sRequestIDPrefix = null;
        if (obj instanceof StatusResponseType) {
            String irt = ((StatusResponseType) obj).getInResponseTo();
            if (irt != null) {
                if (irt.length() <= SAML2AuthNConstants.REQUEST_ID_LENGTH) {
                    StringBuffer sbWarn = new StringBuffer("Invalid InResponseTo ID supplied (");
                    sbWarn.append(irt);
                    sbWarn.append(") is must have a length that is at least bigger then: ");
                    sbWarn.append(SAML2AuthNConstants.REQUEST_ID_LENGTH);
                    _logger.warn(sbWarn.toString());

                    throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
                }

                sRequestIDPrefix = irt.substring(0, SAML2AuthNConstants.REQUEST_ID_LENGTH);
                sSessionID = irt.substring(SAML2AuthNConstants.REQUEST_ID_LENGTH); // '_' was added preceding the session ID, so remove.
            }
        } else {
            _logger.debug("Incoming SAML object is not a valid SAML response");
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }

        ISession session = null;
        if (sSessionID != null) {
            //sessionID found
            if (!SessionValidator.validateDefaultSessionId(sSessionID)) {
                StringBuffer sbError = new StringBuffer("Invalid '");
                sbError.append(ISession.ID_NAME);
                sbError.append("' in request: ");
                sbError.append(sSessionID);
                _logger.debug(sbError.toString());
                throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
            }

            session = _sessionFactory.retrieve(sSessionID);

            if (session == null || session.isExpired()) {
                _logger.debug("Could not process SAML response; Session expired");
                throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
            }

            if (session.getAttributes().contains(SAML2AuthNConstants.class,
                    SAML2AuthNConstants.AUTHNREQUEST_ID_PREFIX)) {
                String sSessionRequestIDPrefix = (String) session.getAttributes().get(SAML2AuthNConstants.class,
                        SAML2AuthNConstants.AUTHNREQUEST_ID_PREFIX);

                if (sSessionRequestIDPrefix != null && sRequestIDPrefix != null
                        && !sSessionRequestIDPrefix.equals(sRequestIDPrefix)) {
                    StringBuffer sbError = new StringBuffer(
                            "Invalid InResponseTo session ID prefix in request: expected '");
                    sbError.append(sSessionRequestIDPrefix);
                    sbError.append("' but recieved: ");
                    sbError.append(sRequestIDPrefix);
                    _logger.debug(sbError.toString());
                    throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
                }
            }

            //verify that the response is sent in response to a request sent by the right
            //SAML profile.
        } else {
            //Create session: probably an unsolicited response
            session = _sessionFactory.createSession(DEFAULT_UR_REQUESTOR_ID);

            String sTarget = null;
            String sRelayState = context.getRelayState();
            if (sRelayState == null) {
                //try SAML 1.1 TARGET parameter:
                sTarget = servletRequest.getParameter("TARGET");
                if (sTarget == null) {
                    //No relaystate and no target: Error!
                    _logger.debug("No session ID and no target found in SAML response");
                    throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
                }
            } else {

                sTarget = sRelayState;
            }

            session.getAttributes().put(ResponseEndpoint.class, SAML2AuthNConstants.ATTR_TARGET, sTarget);
        }

        servletRequest.setAttribute(SAML2AuthNConstants.SESSION_ATTRIBUTE_NAME, context);
        servletRequest.setAttribute(SAML2AuthNConstants.RESPONSE_ENDPOINT_PARAM, new Boolean(true));

        switch (session.getState()) {
        case SESSION_CREATED: {
            processUnsolicitedResponse(servletRequest, servletResponse, session);
            break;
        }
        case USER_LOGOUT_IN_PROGRESS: {
            processLogoutResponse(servletRequest, servletResponse, session);
            break;
        }
        default: {
            processAuthNResponse(servletRequest, servletResponse, session);
        }
        }
    } catch (SAML2SecurityException e) {
        _logger.debug("Error processing SAML message for: " + sRequestorId, e);
        _eventLogger.info(
                new RequestorEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(),
                        null, this, "Error processing SAML message for: " + sRequestorId));
        try {
            if (!servletResponse.isCommitted())
                servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (OAException e) {
        _logger.error("Could not process Response", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null,
                servletRequest.getRemoteAddr(), null, this, null));
        throw e;
    } catch (Exception e) {
        _logger.error("Could not process Response", e);
        _eventLogger.info(new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null,
                servletRequest.getRemoteAddr(), null, this, null));
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.alfaariss.oa.profile.aselect.processor.ASelectProcessor.java

/**
 * Processes the incoming calls./*from  w ww.jav a 2 s  .c  o  m*/
 *
 * Supports the following A-Select calls:
 * <br><br>
 * A-Select SP (application) interface (if enabled)
 * <ul>
 * <li>authenticate : <code>request=authenticate</code></li>
 * <li>verify credentials : <code>request=verify_credentials</code></li>
 * <li>logout : no 'request' and no 'rid'</li>
 * </ul>
 * A-Select IDP (Cross A-Select) interface (if enabled)
 * <ul> 
 * <li>authenticate: <code>request=authenticate&local_organization=[local_organization]</code></li>
 * <li>verify credentials: <code>request=verify_credentials&local_organization=[local_organization]</code></li>
 * </ul>
 * User interface
 * <ul>
 * <li>login redirect: <code>request=login1</code></li>
 * <li>authentication response initiated by the Web SSO: no 'request' and 'rid'</li>
 * </ul>
 * 
 * @see IService#service(javax.servlet.http.HttpServletRequest, 
 *     javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest oServletRequest, HttpServletResponse oServletResponse)
        throws OAException {
    try {
        IBinding oBinding = _bindingFactory.getBinding(oServletRequest, oServletResponse);
        if (oBinding == null) {
            _logger.error("Invalid request sent from IP: " + oServletRequest.getRemoteAddr());
            throw new ASelectException(ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        IRequest oRequest = oBinding.getRequest();

        String sLocalOrganization = (String) oRequest.getParameter(PARAM_LOCAL_IDP);
        String sAppID = (String) oRequest.getParameter(PARAM_APPID);
        String sRequestorID = (String) oRequest.getParameter(PARAM_REQUESTORID);
        String sASelectCredentials = (String) oRequest.getParameter(PARAM_ASELECT_CREDENTIALS);
        String sRID = (String) oRequest.getParameter(PARAM_RID);

        String sRequest = (String) oRequest.getParameter("request");
        if (sRequest == null && sRID != null) {
            _logger.debug("Performing Browser request initiated by the Web SSO sent from IP: "
                    + oServletRequest.getRemoteAddr());
            _oBrowserHandler.authenticate(oServletRequest, oServletResponse, oBinding);
        } else if (sRequest == null && sRID == null) {
            _logger.debug("Performing user information Browser request sent from IP: "
                    + oServletRequest.getRemoteAddr());
            _oBrowserHandler.userinformation(oServletRequest, oServletResponse);
        } else if (sRequest == null) {
            _logger.error("No request parameter found in sent from IP: " + oServletRequest.getRemoteAddr());

            throw new ASelectException(ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        } else if (sRequest.equals("authenticate") && _oIDPHandler.isEnabled() && sLocalOrganization != null) {
            _logger.debug(
                    "Performing 'authenticate' IDP request sent from IP: " + oServletRequest.getRemoteAddr());
            _oIDPHandler.authenticate(oServletRequest, oBinding);
        } else if (sRequest.equals("authenticate") && _oSPHandler.isEnabled()) {
            _logger.debug(
                    "Performing 'authenticate' SP request sent from IP: " + oServletRequest.getRemoteAddr());
            _oSPHandler.authenticate(oServletRequest, oBinding);
        } else if (sRequest.equals("verify_credentials") && _oIDPHandler.isEnabled()
                && sLocalOrganization != null) {
            _logger.debug("Performing 'verify_credentials' IDP request sent from IP: "
                    + oServletRequest.getRemoteAddr());
            _oIDPHandler.verifyCredentials(oServletRequest, oBinding);
        } else if (sRequest.equals("verify_credentials")) {
            _logger.debug("Performing 'verify_credentials' SP request sent from IP: "
                    + oServletRequest.getRemoteAddr());
            _oSPHandler.verifyCredentials(oServletRequest, oBinding);
        } else if (sRequest.equals("login1")) {
            _logger.debug(
                    "Performing 'login1' Browser request sent from IP: " + oServletRequest.getRemoteAddr());
            _oBrowserHandler.login1(oServletRequest, oServletResponse, oBinding);
        } else if (sRequest.equals("logout") && sASelectCredentials != null && sLocalOrganization != null) {//synchronous logout
            if (_oIDPHandler.isEnabled()) {
                _logger.debug("Performing 'synchronous logout' request sent from IP: "
                        + oServletRequest.getRemoteAddr());
                _oIDPHandler.doOrganizationSynchronousLogout(oServletRequest, oBinding, sLocalOrganization,
                        sASelectCredentials);
            } else
                _logger.debug("Could not process request: IDP handler disabled");
        } else if (sRequest.equals("logout") && sASelectCredentials != null
                && (sAppID != null || sRequestorID != null)) {//synchronous logout
            if (_oSPHandler.isEnabled()) {
                _logger.debug("Performing 'synchronous logout' request sent from IP: "
                        + oServletRequest.getRemoteAddr());
                _oSPHandler.doRequestorSynchronousLogout(oServletRequest, oBinding, sRequestorID, sAppID,
                        sASelectCredentials);
            } else
                _logger.debug("Could not process request: SP handler disabled");
        } else if (sRequest.equals("logout") && sRID != null) {//asynchronous logout
            _logger.debug("Performing 'asynchronous logout' Browser request sent from IP: "
                    + oServletRequest.getRemoteAddr());
            _oBrowserHandler.logout(oServletRequest, oServletResponse, oBinding);
        } else if (sRequest.equals("slo") && sLocalOrganization != null) {//asynchronous logout
            if (_oIDPHandler.isEnabled()) {
                _logger.debug("Performing 'asynchronous init logout' IDP request sent from IP: "
                        + oServletRequest.getRemoteAddr());
                _oIDPHandler.slo(oServletRequest, oBinding);
            } else
                _logger.debug("Could not process request: IDP handler disabled");
        } else if (sRequest.equals("slo")) {//asynchronous logout
            if (_oSPHandler.isEnabled()) {
                _logger.debug("Performing 'asynchronous init logout' SP request sent from IP: "
                        + oServletRequest.getRemoteAddr());
                _oSPHandler.slo(oServletRequest, oBinding);
            } else
                _logger.debug("Could not process request: SP handler disabled");
        } else {
            if (_logger.isDebugEnabled()) {
                if (_oSPHandler != null)
                    _logger.debug("SP Handler enabled: " + _oSPHandler.isEnabled());

                if (_oIDPHandler != null)
                    _logger.debug("IDP Handler enabled: " + _oIDPHandler.isEnabled());
            }

            //TODO replace by event and debug logging (EVB, MHO)
            StringBuffer sbWarning = new StringBuffer("Invalid request with name: ");
            sbWarning.append(sRequest);
            sbWarning.append(", sent from IP: ");
            sbWarning.append(oServletRequest.getRemoteAddr());
            _logger.error(sbWarning.toString());

            throw new ASelectException(ASelectErrors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }
    } catch (ASelectException e) {
        try {
            if (!oServletResponse.isCommitted())
                oServletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException e1) {
            _logger.warn("Could not send response", e1);
        }
    } catch (Exception e) {
        _logger.fatal("Internal error during request process", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

public boolean dispatchErrorTmlRequest(WGAError error, javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response) {

    try {//from w  w w  .j  av  a 2  s  .c  om

        if (error.getCausingDatabase() == null) {
            return false;
        }

        HttpSession session = request.getSession();

        // Parse request
        WGPRequestPath path = (WGPRequestPath) request.getAttribute(WGACore.ATTRIB_REQUESTPATH);
        if (path == null) {
            path = WGPRequestPath.parseRequest(this, request, response);
            if (path == null)
                return false;
            request.setAttribute(WGACore.ATTRIB_REQUESTPATH, path);
        }

        // Again fetch the wrapped request and response created by the filter, as we are outside it here and we have again the raw request/response object
        HttpServletRequest wrappedRequest = (HttpServletRequest) request
                .getAttribute(WGAFilter.REQATTRIB_REQUEST_WRAPPER);
        if (wrappedRequest != null) {
            request = wrappedRequest;
        }
        HttpServletResponse wrappedResponse = (HttpServletResponse) request
                .getAttribute(WGAFilter.REQATTRIB_RESPONSE_WRAPPER);
        if (wrappedResponse != null) {
            response = wrappedResponse;
        }

        // Determine tml design for this request
        WGA wga = WGA.get(request, response, getCore());
        WGDatabase errorDatabase = getCore().getContentdbs().get(error.getCausingDatabase());
        if (!errorDatabase.isSessionOpen() && !wga.openDatabase(errorDatabase)) {
            return false;
        }

        WGTMLModule tmlLib = determineErrorModule(errorDatabase, wga, error);
        if (tmlLib == null) {
            return false;
        }

        WGContent content = errorDatabase.getDummyContent(path == null ? null : path.getRequestLanguage());

        // Personalize
        TMLUserProfile tmlUserProfile = null;
        WGTransientPortletRegistry portletRegistry = null;
        TMLPortletStateStorage portletStateStorage = null;
        try {
            tmlUserProfile = getCore().getPersManager().prepareUserProfileForRequest(request, response, content,
                    errorDatabase, null, false);
        } catch (Exception e) {
            _log.error("Unable to personalize WebTML request " + path.getCompleteURL(), e);
        }

        // Set context attributes for tml

        request.setAttribute(WGACore.ATTRIB_WGPPATH, path.getPublisherURL());
        request.setAttribute(WGACore.ATTRIB_TAGIDS, new ConcurrentHashMap<String, BaseTagStatus>());
        request.setAttribute(WGACore.ATTRIB_REQUESTURL, path.getCompleteURL());
        request.setAttribute(WGACore.ATTRIB_MIMETYPE, "text/html");
        request.setAttribute(WGACore.ATTRIB_MEDIAKEY, "html");
        request.setAttribute(WGACore.ATTRIB_REQUESTTYPE, REQUESTTYPE_TML);
        request.setAttribute(WGACore.ATTRIB_URI_HASH,
                WGUtils.createMD5HEX(request.getRequestURI().getBytes("UTF-8")));
        request.setAttribute(WGACore.ATTRIB_FORMDATA, null);
        request.setAttribute(WGACore.ATTRIB_OUTER_DESIGN, tmlLib.getName());
        request.setAttribute(WGACore.ATTRIB_OUTER_DESIGN_DB, tmlLib.getDatabase().getDbReference());
        request.setAttribute(WGACore.ATTRIB_COOKIES, fetchHttpCookies(request));

        // TML Cache control
        response.setHeader("Pragma", "No-Cache");
        response.setHeader("Cache-Control", "No-Cache");

        // Prepare WebTML environment
        TMLContext mainContext = new WebTMLEnvironmentBuilder(getCore(), content, request, response,
                tmlUserProfile, null).prepareWebTmlEnvironment();

        // Change path type to TML, so the WebTML rendering works normally
        path.setPathType(WGPRequestPath.TYPE_TML);
        path.setMediaKey(_core.getMediaKey("html"));

        // Dispatch to jsp
        rootDispatch(wga, wga.design(tmlLib.getDatabase()).resolve(tmlLib.getName()), mainContext, "html");

        // Eventually do redirect
        if (request.getAttribute(WGACore.ATTRIB_REDIRECT) != null) {

            if (!response.isCommitted()) {
                if (!session.isNew()) { // on new sessions we must not reset
                                        // the response (#00000147)
                    response.reset();
                }
                response.sendRedirect(String.valueOf(request.getAttribute(WGACore.ATTRIB_REDIRECT)));
            }
        }

        return true;

    } catch (Exception t) {
        getCore().getLog().error("Exception handling error request", t);
        if (!response.isCommitted()) {
            response.reset();
        }
        return false;
    } finally {
        WGFactory.getInstance().closeSessions();
        TMLContext.clearThreadMainContext();
    }
}

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

/**
 * Process the WebSSO HTTP requests./*from  w  w w  .j a v  a 2 s. c  o  m*/
 * <br><br>
 * All requests require a session: 
 * <ol>
 *  <li>Request attribute ({@link ISession#ID_NAME}=<code>session</code>)</li>
 *   <li>Request parameter ({@link ISession#ID_NAME}=<code>session id</code>)</li>
 * </ol> 
 * 
 * <h4>The following session states are processed:</h4>
 * <dl>
 *  <dt>{@link SessionState#SESSION_CREATED}, {@link SessionState#PRE_AUTHZ_IN_PROGRESS}</dt>
 *  <dd>Perform pre authorization</dd>
 *  <dt>{@link SessionState#PRE_AUTHZ_OK}</dt>
 *  <dd>Check SSO TGT</dd>
 *  <dt>{@link SessionState#AUTHN_SELECTION_IN_PROGRESS}</dt>
 *  <dd>Perform authenctication profile selection</dd>
 *  <dt>{@link SessionState#AUTHN_SELECTION_OK}, {@link SessionState#AUTHN_IN_PROGRESS}</dt>
 *  <dd>Perform authenctication profile selection</dd>
 *  <dt><code>default</code></dt>
 *  <dd>All other states are redirected back to the profile used</dd>
 * </dl>
 * 
 * @see com.alfaariss.oa.api.IService#service(
 *  javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse) throws OAException {
    ISession oSession = null;
    try {
        if (!_bStarted) //Check sso state
        {
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        //Disable caching
        HttpUtils.setDisableCachingHttpHeaders(oRequest, oResponse);

        //retrieve session attribute (trusted)
        oSession = (ISession) oRequest.getAttribute(ISession.ID_NAME);

        if (oSession == null) //No session found yet
        {
            //Retrieve session id (not trusted)
            String sId = oRequest.getParameter(ISession.ID_NAME);
            if (sId != null) {
                //TODO session id as cookie? (Erwin)
                if (!SessionValidator.validateDefaultSessionId(sId)) {
                    _systemLogger.warn("Invalid session id in request: " + sId);
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
                oSession = _ssoService.getSession(sId);
            }
            if (oSession == null) //No session found
            {
                //Show default page
                _systemLogger.debug("No valid session found");
                handleStartPage(oRequest, oResponse);
            }
        }

        if (oSession != null) //Session found
        {
            //Check session expiration
            if (oSession.isExpired()) {
                throw new UserException(UserEvent.SESSION_EXPIRED);
            }

            //Check cancelled
            if (oRequest.getParameter("cancel") != null) {
                try {
                    oSession.setState(SessionState.USER_CANCELLED);
                    oSession.persist();
                    _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                            UserEvent.USER_CANCELLED, this, null));
                } catch (OAException e) {
                    _systemLogger.warn("Could not store session");
                    //Wrap exception
                    throw new SSOException(e.getCode(), e);
                }
            }

            /* dopey adds: change locate from request */
            if (oRequest.getParameter(PARAMETER_LANGUAGE_LOCALE) != null) {
                String sNewLocale = oRequest.getParameter(PARAMETER_LANGUAGE_LOCALE);
                if (!sNewLocale.equals("")) {
                    oSession.setLocale(new Locale(sNewLocale));
                    oSession.persist();
                    _systemLogger.info("User changed session 'locale_language' to " + sNewLocale);
                }
            }
            /* end-of-locale-updates */

            RequestorPool oRequestorPool = _ssoService.getRequestorPool(oSession);
            if (oRequestorPool == null) {
                _systemLogger.warn(new SystemLogItem(oSession.getId(), SystemErrors.ERROR_INTERNAL,
                        "Could not retrieve requestor pool from session"));
                throw new SSOException(SystemErrors.ERROR_INTERNAL);
            }

            //switch state
            switch (oSession.getState()) {
            case SESSION_CREATED: {
                List<IAuthenticationProfile> listAuthNProfiles = _ssoService
                        .getAllAuthNProfiles(oRequestorPool);
                if (listAuthNProfiles.isEmpty()) {
                    //DD A requestor pool must be configured with one or more authN profiles 
                    _systemLogger.warn("Not one enabled authentication profile for requestor pool: "
                            + oRequestorPool.getID());
                    throw new SSOException(SystemErrors.ERROR_INTERNAL);
                }

                oSession.setAuthNProfiles(listAuthNProfiles);
                oSession.setState(SessionState.PRE_AUTHZ_IN_PROGRESS);

                if (oRequestorPool.isForcedAuthenticate()) {
                    oSession.setForcedAuthentication(true);
                    _systemLogger.debug("Forced by requestor pool: Force authentication");
                }

                handlePreAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case PRE_AUTHZ_IN_PROGRESS: {
                handlePreAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case PRE_AUTHZ_OK: {
                checkTGT(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case AUTHN_SELECTION_IN_PROGRESS: {
                handleAuthenticationSelection(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case AUTHN_SELECTION_OK:
            case AUTHN_IN_PROGRESS: {
                handleAuthentication(oRequest, oResponse, oSession, oRequestorPool,
                        oSession.getSelectedAuthNProfile());
                break;
            }
            case POST_AUTHZ_IN_PROGRESS: {
                //handle post authz
                handlePostAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case POST_AUTHZ_OK:
            case POST_AUTHZ_FAILED:
            case PRE_AUTHZ_FAILED:
            case AUTHN_SELECTION_FAILED:
            case AUTHN_OK:
            case USER_CANCELLED:
            case AUTHN_FAILED:
            case AUTHN_NOT_SUPPORTED:
            case USER_BLOCKED:
            case USER_UNKNOWN:
            default: //Redirect to profile
            {
                _systemLogger.debug(
                        new SystemLogItem(oSession.getId(), SystemErrors.OK, "Redirect back to Profile"));
                oResponse.sendRedirect(oSession.getProfileURL());
                break;
            }
            }
        }
    } catch (UserException e) //User error
    {
        if (oSession != null)
            _eventLogger
                    .info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), e.getEvent(), this, null));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, e.getEvent(), null,
                    oRequest.getRemoteAddr(), null, this, null));

        if (!oResponse.isCommitted()) {
            try {
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _systemLogger.warn("Could not send response", e1);
            }
        }
    } catch (SSOException e) //Internal error in websso
    {
        //Log to event logging
        if (oSession != null) {
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, null));
        } else {
            _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                    oRequest.getRemoteAddr(), null, this, null));
        }
        handleError(oRequest, oResponse, oSession, e, e.getCode());
    } catch (OAException e) //Internal error in methods
    {
        handleError(oRequest, oResponse, oSession, e, e.getCode());
    } catch (Exception e) //Internal error 
    {
        handleError(oRequest, oResponse, oSession, e, SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java

private void doGetSinglePV(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    PoorMansProfiler pmansProfiler = new PoorMansProfiler();
    String pvName = req.getParameter("pv");

    if (configService.getStartupState() != STARTUP_SEQUENCE.STARTUP_COMPLETE) {
        String msg = "Cannot process data retrieval requests for PV " + pvName
                + " until the appliance has completely started up.";
        logger.error(msg);//from  w  w  w.ja v  a2s  .c  o m
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
        return;
    }

    String startTimeStr = req.getParameter("from");
    String endTimeStr = req.getParameter("to");
    boolean useReduced = false;
    String useReducedStr = req.getParameter("usereduced");
    if (useReducedStr != null && !useReducedStr.equals("")) {
        try {
            useReduced = Boolean.parseBoolean(useReducedStr);
        } catch (Exception ex) {
            logger.error("Exception parsing usereduced", ex);
            useReduced = false;
        }
    }
    String extension = req.getPathInfo().split("\\.")[1];
    logger.info("Mime is " + extension);

    boolean useChunkedEncoding = true;
    String doNotChunkStr = req.getParameter("donotchunk");
    if (doNotChunkStr != null && !doNotChunkStr.equals("false")) {
        logger.info("Turning off HTTP chunked encoding");
        useChunkedEncoding = false;
    }

    boolean fetchLatestMetadata = false;
    String fetchLatestMetadataStr = req.getParameter("fetchLatestMetadata");
    if (fetchLatestMetadataStr != null && fetchLatestMetadataStr.equals("true")) {
        logger.info("Adding a call to the engine to fetch the latest metadata");
        fetchLatestMetadata = true;
    }

    // For data retrieval we need a PV info. However, in case of PV's that have long since retired, we may not want to have PVTypeInfo's in the system.
    // So, we support a template PV that lays out the data sources.
    // During retrieval, you can pass in the PV as a template and we'll clone this and make a temporary copy.
    String retiredPVTemplate = req.getParameter("retiredPVTemplate");

    if (pvName == null) {
        String msg = "PV name is null.";
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    if (pvName.equals(ARCH_APPL_PING_PV)) {
        logger.debug("Processing ping PV - this is used to validate the connection with the client.");
        processPingPV(req, resp);
        return;
    }

    if (pvName.endsWith(".VAL")) {
        int len = pvName.length();
        pvName = pvName.substring(0, len - 4);
        logger.info("Removing .VAL from pvName for request giving " + pvName);
    }

    // ISO datetimes are of the form "2011-02-02T08:00:00.000Z"
    Timestamp end = TimeUtils.plusHours(TimeUtils.now(), 1);
    if (endTimeStr != null) {
        try {
            end = TimeUtils.convertFromISO8601String(endTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                end = TimeUtils.convertFromDateTimeStringWithOffset(endTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time" + endTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    // We get one day by default
    Timestamp start = TimeUtils.minusDays(end, 1);
    if (startTimeStr != null) {
        try {
            start = TimeUtils.convertFromISO8601String(startTimeStr);
        } catch (IllegalArgumentException ex) {
            try {
                start = TimeUtils.convertFromDateTimeStringWithOffset(startTimeStr);
            } catch (IllegalArgumentException ex2) {
                String msg = "Cannot parse time " + startTimeStr;
                logger.warn(msg, ex2);
                resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
                return;
            }
        }
    }

    if (end.before(start)) {
        String msg = "For request, end " + end.toString() + " is before start " + start.toString() + " for pv "
                + pvName;
        logger.error(msg);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    LinkedList<TimeSpan> requestTimes = new LinkedList<TimeSpan>();

    // We can specify a list of time stamp pairs using the optional timeranges parameter
    String timeRangesStr = req.getParameter("timeranges");
    if (timeRangesStr != null) {
        boolean continueWithRequest = parseTimeRanges(resp, pvName, requestTimes, timeRangesStr);
        if (!continueWithRequest) {
            // Cannot parse the time ranges properly; we so abort the request.
            return;
        }

        // Override the start and the end so that the mergededup consumer works correctly.
        start = requestTimes.getFirst().getStartTime();
        end = requestTimes.getLast().getEndTime();

    } else {
        requestTimes.add(new TimeSpan(start, end));
    }

    assert (requestTimes.size() > 0);

    String postProcessorUserArg = req.getParameter("pp");
    if (pvName.contains("(")) {
        if (!pvName.contains(")")) {
            logger.error("Unbalanced paran " + pvName);
            resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        String[] components = pvName.split("[(,)]");
        postProcessorUserArg = components[0];
        pvName = components[1];
        if (components.length > 2) {
            for (int i = 2; i < components.length; i++) {
                postProcessorUserArg = postProcessorUserArg + "_" + components[i];
            }
        }
        logger.info("After parsing the function call syntax pvName is " + pvName
                + " and postProcessorUserArg is " + postProcessorUserArg);
    }

    PostProcessor postProcessor = PostProcessors.findPostProcessor(postProcessorUserArg);

    PVTypeInfo typeInfo = PVNames.determineAppropriatePVTypeInfo(pvName, configService);
    pmansProfiler.mark("After PVTypeInfo");

    if (typeInfo == null && RetrievalState.includeExternalServers(req)) {
        logger.debug("Checking to see if pv " + pvName + " is served by a external Archiver Server");
        typeInfo = checkIfPVisServedByExternalServer(pvName, start, req, resp, useChunkedEncoding);
    }

    if (typeInfo == null) {
        if (resp.isCommitted()) {
            logger.debug("Proxied the data thru an external server for PV " + pvName);
            return;
        }
    }

    if (typeInfo == null) {
        if (retiredPVTemplate != null) {
            PVTypeInfo templateTypeInfo = PVNames.determineAppropriatePVTypeInfo(retiredPVTemplate,
                    configService);
            if (templateTypeInfo != null) {
                typeInfo = new PVTypeInfo(pvName, templateTypeInfo);
                typeInfo.setPaused(true);
                typeInfo.setApplianceIdentity(configService.getMyApplianceInfo().getIdentity());
                // Somehow tell the code downstream that this is a fake typeInfo.
                typeInfo.setSamplingMethod(SamplingMethod.DONT_ARCHIVE);
                logger.debug("Using a template PV for " + pvName + " Need to determine the actual DBR type.");
                setActualDBRTypeFromData(pvName, typeInfo, configService);
            }
        }
    }

    if (typeInfo == null) {
        logger.error("Unable to find typeinfo for pv " + pvName);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (postProcessor == null) {
        if (useReduced) {
            String defaultPPClassName = configService.getInstallationProperties().getProperty(
                    "org.epics.archiverappliance.retrieval.DefaultUseReducedPostProcessor",
                    FirstSamplePP.class.getName());
            logger.debug("Using the default usereduced preprocessor " + defaultPPClassName);
            try {
                postProcessor = (PostProcessor) Class.forName(defaultPPClassName).newInstance();
            } catch (Exception ex) {
                logger.error("Exception constructing new instance of post processor " + defaultPPClassName, ex);
                postProcessor = null;
            }
        }
    }

    if (postProcessor == null) {
        logger.debug("Using the default raw preprocessor");
        postProcessor = new DefaultRawPostProcessor();
    }

    ApplianceInfo applianceForPV = configService.getApplianceForPV(pvName);
    if (applianceForPV == null) {
        // TypeInfo cannot be null here...
        assert (typeInfo != null);
        applianceForPV = configService.getAppliance(typeInfo.getApplianceIdentity());
    }

    if (!applianceForPV.equals(configService.getMyApplianceInfo())) {
        // Data for pv is elsewhere. Proxy/redirect and return.
        proxyRetrievalRequest(req, resp, pvName, useChunkedEncoding,
                applianceForPV.getRetrievalURL() + "/../data");
        return;
    }

    pmansProfiler.mark("After Appliance Info");

    String pvNameFromRequest = pvName;

    String fieldName = PVNames.getFieldName(pvName);
    if (fieldName != null && !fieldName.equals("") && !pvName.equals(typeInfo.getPvName())) {
        logger.debug("We reset the pvName " + pvName + " to one from the typeinfo " + typeInfo.getPvName()
                + " as that determines the name of the stream. Also using ExtraFieldsPostProcessor");
        pvName = typeInfo.getPvName();
        postProcessor = new ExtraFieldsPostProcessor(fieldName);
    }

    try {
        // Postprocessors get their mandatory arguments from the request.
        // If user does not pass in the expected request, throw an exception.
        postProcessor.initialize(postProcessorUserArg, pvName);
    } catch (Exception ex) {
        logger.error("Postprocessor threw an exception during initialization for " + pvName, ex);
        resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try (BasicContext retrievalContext = new BasicContext(typeInfo.getDBRType(), pvNameFromRequest);
            MergeDedupConsumer mergeDedupCountingConsumer = createMergeDedupConsumer(resp, extension,
                    useChunkedEncoding);
            RetrievalExecutorResult executorResult = determineExecutorForPostProcessing(pvName, typeInfo,
                    requestTimes, req, postProcessor)) {
        HashMap<String, String> engineMetadata = null;
        if (fetchLatestMetadata) {
            // Make a call to the engine to fetch the latest metadata.
            engineMetadata = fetchLatestMedataFromEngine(pvName, applianceForPV);
        }

        LinkedList<Future<RetrievalResult>> retrievalResultFutures = resolveAllDataSources(pvName, typeInfo,
                postProcessor, applianceForPV, retrievalContext, executorResult, req, resp);
        pmansProfiler.mark("After data source resolution");

        long s1 = System.currentTimeMillis();
        String currentlyProcessingPV = null;

        List<Future<EventStream>> eventStreamFutures = getEventStreamFuturesFromRetrievalResults(executorResult,
                retrievalResultFutures);

        logger.debug(
                "Done with the RetrievalResult's; moving onto the individual event stream from each source for "
                        + pvName);
        pmansProfiler.mark("After retrieval results");

        for (Future<EventStream> future : eventStreamFutures) {
            EventStreamDesc sourceDesc = null;
            try (EventStream eventStream = future.get()) {
                sourceDesc = null; // Reset it for each loop iteration.
                sourceDesc = eventStream.getDescription();
                if (sourceDesc == null) {
                    logger.warn("Skipping event stream without a desc for pv " + pvName);
                    continue;
                }

                logger.debug("Processing event stream for pv " + pvName + " from source "
                        + ((eventStream.getDescription() != null) ? eventStream.getDescription().getSource()
                                : " unknown"));

                try {
                    mergeTypeInfo(typeInfo, sourceDesc, engineMetadata);
                } catch (MismatchedDBRTypeException mex) {
                    logger.error(mex.getMessage(), mex);
                    continue;
                }

                if (currentlyProcessingPV == null || !currentlyProcessingPV.equals(pvName)) {
                    logger.debug("Switching to new PV " + pvName
                            + " In some mime responses we insert special headers at the beginning of the response. Calling the hook for that");
                    currentlyProcessingPV = pvName;
                    mergeDedupCountingConsumer.processingPV(currentlyProcessingPV, start, end,
                            (eventStream != null) ? sourceDesc : null);
                }

                try {
                    // If the postProcessor does not have a consolidated event stream, we send each eventstream across as we encounter it.
                    // Else we send the consolidatedEventStream down below.
                    if (!(postProcessor instanceof PostProcessorWithConsolidatedEventStream)) {
                        mergeDedupCountingConsumer.consumeEventStream(eventStream);
                        resp.flushBuffer();
                    }
                } catch (Exception ex) {
                    if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
                        // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                        logger.debug(
                                "Exception when consuming and flushing data from " + sourceDesc.getSource(),
                                ex);
                    } else {
                        logger.error("Exception when consuming and flushing data from " + sourceDesc.getSource()
                                + "-->" + ex.toString(), ex);
                    }
                }
                pmansProfiler.mark("After event stream " + eventStream.getDescription().getSource());
            } catch (Exception ex) {
                if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
                    // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
                    logger.debug("Exception when consuming and flushing data from "
                            + (sourceDesc != null ? sourceDesc.getSource() : "N/A"), ex);
                } else {
                    logger.error("Exception when consuming and flushing data from "
                            + (sourceDesc != null ? sourceDesc.getSource() : "N/A") + "-->" + ex.toString(),
                            ex);
                }
            }
        }

        if (postProcessor instanceof PostProcessorWithConsolidatedEventStream) {
            try (EventStream eventStream = ((PostProcessorWithConsolidatedEventStream) postProcessor)
                    .getConsolidatedEventStream()) {
                EventStreamDesc sourceDesc = eventStream.getDescription();
                if (sourceDesc == null) {
                    logger.error("Skipping event stream without a desc for pv " + pvName
                            + " and post processor " + postProcessor.getExtension());
                } else {
                    mergeDedupCountingConsumer.consumeEventStream(eventStream);
                    resp.flushBuffer();
                }
            }
        }

        // If the postProcessor needs to send final data across, give it a chance now...
        if (postProcessor instanceof AfterAllStreams) {
            EventStream finalEventStream = ((AfterAllStreams) postProcessor).anyFinalData();
            if (finalEventStream != null) {
                mergeDedupCountingConsumer.consumeEventStream(finalEventStream);
                resp.flushBuffer();
            }
        }

        pmansProfiler.mark("After writing all eventstreams to response");

        long s2 = System.currentTimeMillis();
        logger.info("For the complete request, found a total of "
                + mergeDedupCountingConsumer.totalEventsForAllPVs + " in " + (s2 - s1) + "(ms)" + " skipping "
                + mergeDedupCountingConsumer.skippedEventsForAllPVs + " events" + " deduping involved "
                + mergeDedupCountingConsumer.comparedEventsForAllPVs + " compares.");
    } catch (Exception ex) {
        if (ex != null && ex.toString() != null && ex.toString().contains("ClientAbortException")) {
            // We check for ClientAbortException etc this way to avoid including tomcat jars in the build path.
            logger.debug("Exception when retrieving data ", ex);
        } else {
            logger.error("Exception when retrieving data " + "-->" + ex.toString(), ex);
        }
    }
    pmansProfiler.mark("After all closes and flushing all buffers");

    // Till we determine all the if conditions where we log this, we log sparingly..
    if (pmansProfiler.totalTimeMS() > 5000) {
        logger.error("Retrieval time for " + pvName + " from " + startTimeStr + " to " + endTimeStr
                + pmansProfiler.toString());
    }
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    Throwable rootExn = e;/*from  w w  w. j  a v a  2 s.  c  om*/
    Throwable errorPageExn = null;
    LineMap lineMap = null;

    try {
        response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
        AsyncContext async = req.getAsyncContext();

        if (async != null)
            async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
        HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
        resFacade.killCache();
        resFacade.setNoCache(true);
    }

    if (rootExn instanceof ClientDisconnectException)
        throw (ClientDisconnectException) rootExn;

    String location = null;

    String title = "500 Servlet Exception";
    boolean isBadRequest = false;
    boolean doStackTrace = true;
    boolean isCompileException = false;
    boolean isServletException = false;
    Throwable compileException = null;
    String lineMessage = null;

    boolean lookupErrorPage = true;

    while (true) {
        if (rootExn instanceof LineMapException)
            lineMap = ((LineMapException) rootExn).getLineMap();

        if (lookupErrorPage) {
            errorPageExn = rootExn;
        }

        if (rootExn instanceof DisplayableException) {
            doStackTrace = false;
            isCompileException = true;
            if (compileException == null)
                compileException = rootExn;
        } else if (rootExn instanceof CompileException) {
            doStackTrace = false;
            isCompileException = true;

            if (compileException == null) // ! isLineCompileException)
                compileException = rootExn;
        } else if (rootExn instanceof LineException) {
            if (lineMessage == null)
                lineMessage = rootExn.getMessage();
        }

        if (rootExn instanceof BadRequestException) {
            isBadRequest = true;
        }

        if (rootExn instanceof OutOfMemoryError) {
            String msg = "TcpSocketLink OutOfMemory";

            ShutdownSystem.shutdownOutOfMemory(msg);
        }

        if (location != null || !lookupErrorPage) {
        } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException
                && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) {
            // hack to deal with JSP wrapping
        } else if (!isServletException) {
            // SRV.9.9.2 Servlet 2.4
            // location = getErrorPage(rootExn, ServletException.class);
            location = getErrorPage(rootExn);
            isServletException = true;
        } else {
            location = getErrorPage(rootExn);
            lookupErrorPage = false;
        }

        if (location != null)
            lookupErrorPage = false;

        if (isBadRequest)
            break;

        Throwable cause = null;
        if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException))
            cause = ((ServletException) rootExn).getRootCause();
        else {
            lookupErrorPage = false;
            cause = rootExn.getCause();
        }

        if (cause != null)
            rootExn = cause;
        else {
            break;
        }
    }

    if (location == null && lookupErrorPage) {
        location = getErrorPage(rootExn);
    }

    if (location == null)
        location = getErrorPage(500);

    if (isBadRequest) {
        // server/05a0, server/0532

        if (rootExn instanceof CompileException)
            title = rootExn.getMessage();
        else
            title = String.valueOf(rootExn);

        doStackTrace = false;
        isBadRequest = true;

        if (request instanceof CauchoRequest)
            ((CauchoRequest) request).killKeepalive("bad request: " + rootExn);

        response.resetBuffer();

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        /*
         * if (location == null) log.warn(e.toString());
         */
    } else if (rootExn instanceof UnavailableException) {
        UnavailableException unAvail = (UnavailableException) rootExn;

        if (unAvail.isPermanent()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            title = "404 Not Found";

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            title = "503 Unavailable";

            if (unAvail.getUnavailableSeconds() > 0)
                response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds());

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (location == null)
        location = _defaultLocation;

    if (log.isTraceEnabled())
        log.trace(e.toString(), e);
    else if (isCompileException) {
        if (isBadRequest)
            log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage());
        else
            log.trace(compileException.getMessage());
    } else if (!doStackTrace)
        log.trace(rootExn.toString());
    else
        log.trace(e.toString(), e);

    if (location != null) {
        if (errorPageExn == null)
            errorPageExn = rootExn;

        request.setAttribute(JSP_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass());
        if (request instanceof HttpServletRequest)
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                    ((HttpServletRequest) request).getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage());

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.

            WebApp webApp = getWebApp();

            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
                return;
            }
        } catch (Throwable e1) {
            log.info(e1.toString(), e1);
            rootExn = e1;
        }
    }

    response.setContentType("text/html");

    String encoding = CharacterEncoding.getLocalEncoding();

    if (encoding != null)
        response.setCharacterEncoding(encoding);
    else {
        Locale locale = Locale.getDefault();
        if (!"ISO-8859-1".equals(Encoding.getMimeName(locale)))
            response.setLocale(Locale.getDefault());
        else
            response.setCharacterEncoding("utf-8");
    }

    PrintWriter out;

    try {
        out = response.getWriter();
    } catch (IllegalStateException e1) {
        log.trace(e1.toString(), e1);

        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
    }

    if (isDevelopmentModeErrorPage()) {
        out.println("<html>");
        if (!response.isCommitted())
            out.println("<head><title>" + escapeHtml(title) + "</title></head>");
        out.println("<body>");
        out.println("<h1>" + escapeHtml(title) + "</h1>");

        out.println("<code><pre>");

        if (debug && !CurrentTime.isTest())
            doStackTrace = true;

        if (doStackTrace) {
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("function show() { document.getElementById('trace').style.display = ''; }");
            out.println("</script>");
            out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> ");
        }

        if (compileException instanceof DisplayableException) {
            // ioc/0000
            // XXX: dispExn.print doesn't normalize user.name
            // dispExn.print(out);
            out.println(escapeHtml(compileException.getMessage()));
        } else if (compileException != null)
            out.println(escapeHtml(compileException.getMessage()));
        else
            out.println(escapeHtml(rootExn.toString()));

        if (doStackTrace) {
            out.println("<span id=\"trace\" style=\"display:none\">");
            printStackTrace(out, lineMessage, e, rootExn, lineMap);
            out.println("</span>");
        }

        /*
         * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); }
         */

        out.println("</pre></code>");

        printVersion(out);

        out.println("</body></html>");
    } else { // non-development mode
        out.println("<html>");
        out.println("<title>Server Error</title>");
        out.println("<body>");
        out.println("<h1>Server Error</h1>");
        out.println("<p>The server is temporarily unavailable due to an");
        out.println("internal error.  Please notify the system administrator");
        out.println("of this problem.</p>");

        out.println("<pre><code>");
        out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime()));

        out.println("</code></pre>");

        printVersion(out);

        out.println("</body></html>");
    }

    String userAgent = request.getHeader("User-Agent");

    if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
        out.print(MSIE_PADDING);
    }

    out.close();
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

/**
 * Handle Metadata updating/*from w  w w  .j  a  va  2  s. c  o m*/
 */
public void handleMeta(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    if (target.equals(Constants.API_ENDPOINT_META)) {
        baseRequest.setHandled(true);
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);

            forwarded = true;
        }

        //
        // Loop over the input lines.
        // Each has the following format:
        //
        // class{labels}{attributes}
        //

        String token = null != dr ? dr.getToken()
                : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));

        WriteToken wtoken;

        try {
            wtoken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = wtoken.getAppName();
        String producer = Tokens.getUUID(wtoken.getProducerId());
        String owner = Tokens.getUUID(wtoken.getOwnerId());

        if (null == producer || null == owner) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
            return;
        }

        //
        // Determine if content if gzipped
        //

        boolean gzipped = false;

        if (null != request.getHeader("Content-Type")
                && "application/gzip".equals(request.getHeader("Content-Type"))) {
            gzipped = true;
        }

        BufferedReader br = null;

        if (gzipped) {
            GZIPInputStream is = new GZIPInputStream(request.getInputStream());
            br = new BufferedReader(new InputStreamReader(is));
        } else {
            br = request.getReader();
        }

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        //
        // Open the logging file if logging is enabled
        //

        if (null != loggingDir) {
            long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
            StringBuilder sb = new StringBuilder();
            sb.append(Long.toHexString(nanos));
            sb.insert(0, "0000000000000000", 0, 16 - sb.length());
            sb.append("-");
            if (null != dr) {
                sb.append(dr.getId());
            } else {
                sb.append(datalogId);
            }

            sb.append("-");
            sb.append(dtf.print(nanos / 1000000L));
            sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
            sb.append("Z");

            if (null == dr) {
                dr = new DatalogRequest();
                dr.setTimestamp(nanos);
                dr.setType(Constants.DATALOG_META);
                dr.setId(datalogId);
                dr.setToken(token);
            }

            if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {
                //
                // Serialize the request
                //

                TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                byte[] encoded;

                try {
                    encoded = ser.serialize(dr);
                } catch (TException te) {
                    throw new IOException(te);
                }

                if (null != this.datalogPSK) {
                    encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                }

                encoded = OrderPreservingBase64.encode(encoded);

                loggingFile = new File(loggingDir, sb.toString());
                loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                //
                // Write request
                //

                loggingWriter.println(new String(encoded, Charsets.US_ASCII));
            }
        }

        try {
            //
            // Loop on all lines
            //

            while (true) {
                String line = br.readLine();

                if (null == line) {
                    break;
                }

                // Ignore blank lines
                if ("".equals(line)) {
                    continue;
                }

                // Ignore comments
                if ('#' == line.charAt(0)) {
                    continue;
                }

                Metadata metadata = MetadataUtils.parseMetadata(line);

                // Add labels from the WriteToken if they exist
                if (wtoken.getLabelsSize() > 0) {
                    metadata.getLabels().putAll(wtoken.getLabels());
                }
                //
                // Force owner/producer
                //

                metadata.getLabels().put(Constants.PRODUCER_LABEL, producer);
                metadata.getLabels().put(Constants.OWNER_LABEL, owner);

                if (null != application) {
                    metadata.getLabels().put(Constants.APPLICATION_LABEL, application);
                } else {
                    // remove application label
                    metadata.getLabels().remove(Constants.APPLICATION_LABEL);
                }

                if (!MetadataUtils.validateMetadata(metadata)) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid metadata " + line);
                    return;
                }

                metadata.setSource(Configuration.INGRESS_METADATA_UPDATE_ENDPOINT);
                this.directoryClient.register(metadata);

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            }
        } finally {
            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Process a POST to the servlet by handing it off to the Axis Engine.
 * Here is where SOAP messages are received
 * @param req posted request//ww  w. jav a  2  s. co m
 * @param res respose
 * @throws ServletException trouble
 * @throws IOException different trouble
 */
public void doPost(HttpServletRequest req, HttpServletResponse res, Component component)
        throws ServletException, IOException {
    long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
    String soapAction = null;
    MessageContext msgContext = null;

    Message rspMsg = null;
    String contentType = null;
    InputStream is = null;
    try {
        AxisEngine engine = getEngine();

        if (engine == null) {
            // !!! should return a SOAP fault...
            ServletException se = new ServletException(Messages.getMessage("noEngine00"));
            log.debug("No Engine!", se);
            throw se;
        }

        res.setBufferSize(1024 * 8); // provide performance boost.

        /** get message context w/ various properties set
         */
        msgContext = createMessageContext(engine, req, res, component);
        ComponentController.set(msgContext);

        // ? OK to move this to 'getMessageContext',
        // ? where it would also be picked up for 'doGet()' ?
        if (securityProvider != null) {
            if (isDebug) {
                log.debug("securityProvider:" + securityProvider);
            }
            msgContext.setProperty(MessageContext.SECURITY_PROVIDER, securityProvider);
        }

        is = req.getInputStream();
        Message requestMsg = new Message(is, false, req.getHeader(HTTPConstants.HEADER_CONTENT_TYPE),
                req.getHeader(HTTPConstants.HEADER_CONTENT_LOCATION));
        // Transfer HTTP headers to MIME headers for request message.
        MimeHeaders requestMimeHeaders = requestMsg.getMimeHeaders();
        for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            for (Enumeration f = req.getHeaders(headerName); f.hasMoreElements();) {
                String headerValue = (String) f.nextElement();
                requestMimeHeaders.addHeader(headerName, headerValue);
            }
        }

        if (isDebug) {
            log.debug("Request Message:" + requestMsg);

            /* Set the request(incoming) message field in the context */
            /**********************************************************/
        }
        msgContext.setRequestMessage(requestMsg);
        String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
        msgContext.setProperty(MessageContext.TRANS_URL, url);
        // put character encoding of request to message context
        // in order to reuse it during the whole process.

        try {
            String reqEnc = (String) requestMsg.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
            if (reqEnc != null)
                msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, reqEnc);
        } catch (SOAPException e1) {
        }

        try {
            /**
             * Save the SOAPAction header in the MessageContext bag.
             * This will be used to tell the Axis Engine which service
             * is being invoked.  This will save us the trouble of
             * having to parse the Request message - although we will
             * need to double-check later on that the SOAPAction header
             * does in fact match the URI in the body.
             */
            // (is this last stmt true??? (I don't think so - Glen))
            /********************************************************/
            soapAction = getSoapAction(req);
            if (soapAction != null) {
                msgContext.setUseSOAPAction(true);
                msgContext.setSOAPActionURI(soapAction);
            }

            // Create a Session wrapper for the HTTP session.
            // These can/should be pooled at some point.
            // (Sam is Watching! :-)
            msgContext.setSession(new AxisHttpSession(req));

            if (tlog.isDebugEnabled()) {
                t1 = System.currentTimeMillis();
            }
            /* Invoke the Axis engine... */
            /*****************************/
            if (isDebug) {
                log.debug("Invoking Axis Engine.");
                //here we run the message by the engine
            }
            //msgContext.setProperty("disablePrettyXML", "false");
            engine.invoke(msgContext);
            if (isDebug) {
                log.debug("Return from Axis Engine.");
            }
            if (tlog.isDebugEnabled()) {
                t2 = System.currentTimeMillis();
            }

            rspMsg = msgContext.getResponseMessage();

            // We used to throw exceptions on null response messages.
            // They are actually OK in certain situations (asynchronous
            // services), so fall through here and return an ACCEPTED
            // status code below.  Might want to install a configurable
            // error check for this later.
        } catch (AxisFault fault) {

            //log and sanitize
            processAxisFault(fault);
            configureResponseFromAxisFault(res, fault);
            rspMsg = msgContext.getResponseMessage();
            if (rspMsg == null) {
                rspMsg = new Message(fault);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException)
                t = ((InvocationTargetException) t).getTargetException();
            // Exception
            if (t instanceof Exception) {
                Exception e = (Exception) t;
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = convertExceptionToAxisFault(e, rspMsg);
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);

            }
            // throwable
            else {
                logException(t);
                //other exceptions are internal trouble
                rspMsg = msgContext.getResponseMessage();
                res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rspMsg = new Message(new AxisFault(t.toString(), t));
                ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
            }
        }
    } catch (AxisFault fault) {

        processAxisFault(fault);
        configureResponseFromAxisFault(res, fault);
        rspMsg = msgContext.getResponseMessage();
        if (rspMsg == null) {
            rspMsg = new Message(fault);
            ((org.apache.axis.SOAPPart) rspMsg.getSOAPPart()).getMessage().setMessageContext(msgContext);
        }
    } finally {
        IOUtil.closeEL(is);
    }

    if (tlog.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
    }

    // Send response back along the wire... 
    if (rspMsg != null) {

        // Transfer MIME headers to HTTP headers for response message.
        MimeHeaders responseMimeHeaders = rspMsg.getMimeHeaders();
        for (Iterator i = responseMimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader responseMimeHeader = (MimeHeader) i.next();
            res.addHeader(responseMimeHeader.getName(), responseMimeHeader.getValue());
        }
        // synchronize the character encoding of request and response
        String responseEncoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
        if (responseEncoding != null) {
            try {
                rspMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, responseEncoding);
            } catch (SOAPException e) {
            }
        }

        //determine content type from message response
        contentType = rspMsg.getContentType(msgContext.getSOAPConstants());
        if (isDebug)
            log.debug("Returned Content-Type:" + contentType);

        // write result to response stream
        try {
            res.setContentType(contentType);
            rspMsg.writeTo(res.getOutputStream());
        } catch (SOAPException e) {
            logException(e);
        }

        if (!res.isCommitted())
            res.flushBuffer(); // Force it right now.
    } else {
        // No content, so just indicate accepted
        res.setStatus(202);
    }

    if (isDebug) {
        log.debug("Response sent.");
        log.debug("Exit: doPost()");
    }
    if (tlog.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        tlog.debug("axisServlet.doPost: " + soapAction + " pre=" + (t1 - t0) + " invoke=" + (t2 - t1) + " post="
                + (t3 - t2) + " send=" + (t4 - t3) + " " + msgContext.getTargetService() + "."
                + ((msgContext.getOperation() == null) ? "" : msgContext.getOperation().getName()));
    }

}