Example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

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

Introduction

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

Prototype

int SC_SERVICE_UNAVAILABLE

To view the source code for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE.

Click Source Link

Document

Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.

Usage

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Retrieves a JSON representation of a <tt>Conference</tt> with ID
 * <tt>target</tt> of (the associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> of (the associated)
 * <tt>Videobridge</tt> to represent in JSON format
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request/*from  w w w  .  j  ava 2  s  .  c  om*/
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        // We allow requests for certain sub-resources of a Conference
        // though such as DominantSpeakerIdentification.
        int conferenceIDEndIndex = target.indexOf('/');
        String conferenceID = target;

        if ((conferenceIDEndIndex > 0) && (conferenceIDEndIndex < target.length() - 1)) {
            target = target.substring(conferenceIDEndIndex + 1);
            if (DOMINANT_SPEAKER_IDENTIFICATION.equals(target)) {
                conferenceID = conferenceID.substring(0, conferenceIDEndIndex);
            }
        }

        Conference conference = videobridge.getConference(conferenceID, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (DOMINANT_SPEAKER_IDENTIFICATION.equals(target)) {
            doGetDominantSpeakerIdentificationJSON(conference, baseRequest, request, response);
        } else {
            ColibriConferenceIQ conferenceIQ = new ColibriConferenceIQ();

            conference.describeDeep(conferenceIQ);

            JSONObject conferenceJSONObject = JSONSerializer.serializeConference(conferenceIQ);

            if (conferenceJSONObject == null) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                conferenceJSONObject.writeJSONString(response.getWriter());
            }
        }
    }
}

From source file:org.bibsonomy.webapp.util.spring.controller.MinimalisticControllerSpringWrapper.java

/**
 * instantiates, initializes and runs the MinimalisticController
 * //from   ww  w.jav  a2 s .co m
 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    ((RequestLogic) getApplicationContext().getBean("requestLogic")).setRequest(request); // hack but thats springs fault
    ((ResponseLogic) getApplicationContext().getBean("responseLogic")).setResponse(response); // hack but thats springs fault
    final MinimalisticController<T> controller = (MinimalisticController<T>) getApplicationContext()
            .getBean(controllerBeanName);
    /**
     * Controller is put into request.
     * 
     * FIXME: is this still neccessary?
     * 
     * SuppressValidation retrieves controller from request again!
     */
    request.setAttribute(CONTROLLER_ATTR_NAME, controller);

    /*
     * DEBUG: log request attributes
     */
    if (log.isDebugEnabled()) {
        final Enumeration<?> e = request.getAttributeNames();
        while (e.hasMoreElements()) {
            log.debug(e.nextElement().toString());
        }
    }

    final T command = controller.instantiateCommand();

    /*
     * put context into command
     * 
     * TODO: in the future this is hopefully no longer needed, since the wrapper
     * only exists to transfer request attributes into the command.
     */
    command.setContext((RequestWrapperContext) request.getAttribute(RequestWrapperContext.class.getName()));

    /*
     * set validator for this instance
     */
    if (controller instanceof ValidationAwareController<?>) {
        this.setValidator(((ValidationAwareController<T>) controller).getValidator());
    }

    /*
     * bind request attributes to command
     */
    final ServletRequestDataBinder binder = bindAndValidate(request, command);
    final BindException errors = new BindException(binder.getBindingResult());
    if (controller instanceof ErrorAware) {
        ((ErrorAware) controller).setErrors(errors);
    }

    View view;

    /*
     * define error view
     */
    if (controller instanceof AjaxController) {
        view = Views.AJAX_ERRORS;
    } else {
        view = Views.ERROR;
    }

    try {
        view = controller.workOn(command);
    } catch (final MalformedURLSchemeException malformed) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.http.notFound", malformed.getMessage());
        log.warn("Could not complete controller (invalid URL scheme) : " + malformed.getMessage());
    } catch (final AccessDeniedException ad) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        errors.reject(ad.getMessage());
        log.warn("Could not complete controller (AccessDeniedException), occured in: " + ad.getStackTrace()[0]
                + ", msg is: " + ad.getMessage());
    } catch (final ServiceUnavailableException e) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.setHeader("Retry-After", Long.toString(e.getRetryAfter()));
        errors.reject(e.getMessage(), new Object[] { e.getRetryAfter() }, "Service unavailable");
        /*
         *  this exception is only thrown in UserLoginController
         *  if desired, add some logging there. Otherwise, our error logs get
         *  cluttered.(dbe)
         */
        // log.warn("Could not complete controller (Service unavailable): " + e.getMessage());
    } catch (final ResourceMovedException e) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location",
                urlGenerator.getPostUrl(e.getResourceType(), e.getNewIntraHash(), e.getUserName()));
    } catch (final ResourceNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.post.notfound", e.getMessage()); // FIXME: it would be better, to show the specific 404 view
    } catch (final org.springframework.security.access.AccessDeniedException ex) {
        /*
         * we rethrow the exception here in order that Spring Security can
         * handle the exception (saving request and redirecting to the login
         * page (if user is not logged in) or to the access denied page)
         */
        throw ex;
    } catch (final Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors.reject("error.internal", new Object[] { ex }, "Internal Server Error: " + ex.getMessage());
        log.error("Could not complete controller (general exception) for request /" + request.getRequestURI()
                + "?" + request.getQueryString() + " with referer " + request.getHeader("Referer"), ex);
    }

    log.debug("Exception catching block passed, putting comand+errors into model.");

    final Map<String, Object> model = new HashMap<String, Object>();
    model.put(getCommandName(), command);

    /*
     * put errors into model 
     */
    model.putAll(errors.getModel());

    log.debug("Returning model and view.");

    /**
     * If the view is already a Spring view, use it directly.
     * The primal reason for the this workaround is, that Spring's RedirctView
     * automatically appends the model parameters to each redirected URL. This
     * can only be avoided by calling setExposeModelAttributes(false) on the 
     * RedirectView. Hence, we must directly create a redirect view instead of 
     * using a "redirect:..." URL.  
     */
    if (org.springframework.web.servlet.View.class.isAssignableFrom(view.getClass())) {
        return new ModelAndView((org.springframework.web.servlet.View) view, model);
    }

    return new ModelAndView(view.getName(), model);
}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

CloudFrontResponse invoke(String... args) throws CloudFrontException, CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("Context not specified for this request");
    }// w ww. j  a va2  s.c  o  m
    StringBuilder url = new StringBuilder();
    String dateString = getDate();
    HttpRequestBase method;
    HttpClient client;

    url.append(CLOUD_FRONT_URL + "/" + CF_VERSION + "/distribution");
    if (args != null && args.length > 0) {
        for (String arg : args) {
            url.append("/");
            url.append(arg);
        }
    }
    method = action.getMethod(url.toString());
    method.addHeader(AWSCloud.P_AWS_DATE, dateString);
    try {
        String signature = provider.signCloudFront(new String(ctx.getAccessPublic(), "utf-8"),
                ctx.getAccessPrivate(), dateString);

        method.addHeader(AWSCloud.P_CFAUTH, signature);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (body != null) {
        try {
            ((HttpEntityEnclosingRequestBase) method)
                    .setEntity(new StringEntity(body, "application/xml", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    attempts++;
    client = getClient(url.toString());
    CloudFrontResponse response = new CloudFrontResponse();

    HttpResponse httpResponse;
    int status;

    try {
        APITrace.trace(provider, action.toString());
        httpResponse = client.execute(method);
        status = httpResponse.getStatusLine().getStatusCode();

    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    Header header = httpResponse.getFirstHeader("ETag");

    if (header != null) {
        response.etag = header.getValue();
    } else {
        response.etag = null;
    }
    if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_CREATED
            || status == HttpServletResponse.SC_ACCEPTED) {
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            try {
                response.document = parseResponse(input);
                return response;
            } finally {
                input.close();
            }
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    } else if (status == HttpServletResponse.SC_NO_CONTENT) {
        return null;
    } else {
        if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            if (attempts >= 5) {
                String msg;

                if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                    msg = "Cloud service is currently unavailable.";
                } else {
                    msg = "The cloud service encountered a server error while processing your request.";
                }
                logger.error(msg);
                throw new CloudException(msg);
            } else {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
                return invoke(args);
            }
        }
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            Document doc;

            try {
                doc = parseResponse(input);
            } finally {
                input.close();
            }
            if (doc != null) {
                String code = null, message = null, requestId = null, type = null;
                NodeList blocks = doc.getElementsByTagName("Error");

                if (blocks.getLength() > 0) {
                    Node error = blocks.item(0);
                    NodeList attrs;

                    attrs = error.getChildNodes();
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);

                        if (attr.getNodeName().equals("Code")) {
                            code = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Type")) {
                            type = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Message")) {
                            message = attr.getFirstChild().getNodeValue().trim();
                        }
                    }

                }
                blocks = doc.getElementsByTagName("RequestId");
                if (blocks.getLength() > 0) {
                    Node id = blocks.item(0);

                    requestId = id.getFirstChild().getNodeValue().trim();
                }
                if (message == null) {
                    throw new CloudException(
                            "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                }
                throw new CloudFrontException(status, requestId, type, code, message);
            }
            throw new CloudException("Unable to parse error.");
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    }
}

From source file:TestHTTPSource.java

@Test
public void testFullChannel() throws Exception {
    HttpResponse response = putWithEncoding("UTF-8", 150).response;
    Assert.assertEquals(HttpServletResponse.SC_SERVICE_UNAVAILABLE, response.getStatusLine().getStatusCode());
}

From source file:org.apache.jasper.servlet.JspServletWrapper.java

public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile)
        throws ServletException, IOException, FileNotFoundException {
    try {//from   w w w. j a  v a  2  s.  c  o  m

        if (ctxt.isRemoved()) {
            throw new FileNotFoundException(jspUri);
        }

        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    Localizer.getMessage("jsp.error.unavailable"));
        }

        if (options.getDevelopment() || firstTime) {
            synchronized (this) {
                ctxt.compile();
            }
        }

        if (reload) {
            getServlet();
        }

        // If a page is to only to be precompiled return.
        if (precompile) {
            return;
        }

        if (theServlet instanceof SingleThreadModel) {
            // sync on the wrapper so that the freshness
            // of the page is determined right before servicing
            synchronized (this) {
                theServlet.service(request, response);
            }
        } else {
            theServlet.service(request, response);
        }

    } catch (UnavailableException ex) {
        String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (includeRequestUri != null) {
            // This file was included. Throw an exception as
            // a response.sendError() will be ignored by the
            // servlet engine.
            throw ex;
        } else {
            int unavailableSeconds = ex.getUnavailableSeconds();
            if (unavailableSeconds <= 0) {
                unavailableSeconds = 60; // Arbitrary default
            }
            available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
        }
    } catch (FileNotFoundException ex) {
        String includeRequestUri = (String) request.getAttribute("javax.servlet.include.request_uri");
        if (includeRequestUri != null) {
            // This file was included. Throw an exception as
            // a response.sendError() will be ignored by the
            // servlet engine.
            throw new ServletException(ex);
        } else {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, ex.getMessage());
            } catch (IllegalStateException ise) {
                log.error(Localizer.getMessage("jsp.error.file.not.found", ex.getMessage()), ex);
            }
        }
    } catch (ServletException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    } catch (IllegalStateException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new JasperException(ex);
    }
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }/*from   w ww. j  ava  2s .  c  om*/
        if (headerNameKey.equals("Content-Type")) {
            contenttype = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.info("contenttype = " + contenttype);

    try {

        // TODO validate Content-Type

        String data = httpServletRequest.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));

        if (data == null || data.equals("")) {

            this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
            httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
        } else {

            String postableData = null;

            // TODO bind interface Preprocessing
            if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

                PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class);
                // init Authorization Service
                preprocessingInterface.init(this.config);

                postableData = preprocessingInterface.process(data);
            } else {

                // TODO correct error handling
                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }

            if (postableData != null) {

                // TODO if successful then POST as application/sparql-update to LinkedDataPlatform
                String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

                // HTTP Request
                int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

                CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultRequestConfig(defaultRequestConfig).build();

                try {

                    HttpPost httpPost = new HttpPost(sparql_url);
                    httpPost.addHeader("Content-Type", "application/sparql-update");
                    httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
                    httpPost.setEntity(new StringEntity(postableData));

                    CloseableHttpResponse httpResponse = null;

                    long start = System.nanoTime();
                    try {

                        httpResponse = httpclient.execute(httpPost);
                    } catch (ConnectTimeoutException | SocketTimeoutException e) {

                        this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": "
                                + e.getMessage());
                        httpResponse = httpclient.execute(httpPost);
                    }
                    long elapsed = System.nanoTime() - start;
                    this.logger.info("[" + this.getClass().getName() + "] LDP request - "
                            + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s");

                    try {

                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        HttpEntity httpEntity = httpResponse.getEntity();

                        // TODO
                        httpServletResponse.setStatus(statusCode);
                        httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase());

                        EntityUtils.consume(httpEntity);

                    } finally {
                        httpResponse.close();
                    }
                } finally {

                    httpclient.close();
                }
            }
        }
    } catch (Exception e) {

        this.logger.error("something went wrong", e);
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
}

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   ww  w. j a v a  2 s .  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:ca.nrc.cadc.web.SearchJobServlet.java

/**
 * Called by the server (via the <code>service</code> method)
 * to allow a servlet to handle a POST request.
 *
 * The HTTP POST method allows the client to send
 * data of unlimited length to the Web server a single time
 * and is useful when posting information such as
 * credit card numbers.//from ww  w . j a v  a 2 s .com
 *
 *When overriding this method, read the request data,
 * write the response headers, get the response's writer or output
 * stream object, and finally, write the response data. It's best
 * to include content type and encoding. When using a
 * <code>PrintWriter</code> object to return the response, set the
 * content type before accessing the <code>PrintWriter</code> object.
 *
 *The servlet container must write the headers before committing the
 * response, because in HTTP the headers must be sent before the
 * response body.
 *
 *Where possible, set the Content-Length header (with the
 * {@link ServletResponse#setContentLength} method),
 * to allow the servlet container to use a persistent connection
 * to return its response to the client, improving performance.
 * The content length is automatically set if the entire response fits
 * inside the response buffer.
 *
 *When using HTTP 1.1 chunked encoding (which means that the response
 * has a Transfer-Encoding header), do not set the Content-Length header.
 *
 *This method does not need to be either safe or idempotent.
 * Operations requested through POST can have side effects for
 * which the user can be held accountable, for example,
 * updating stored data or buying items online.
 *
 *If the HTTP POST request is incorrectly formatted,
 * <code>doPost</code> returns an HTTP "Bad Request" message.
 *
 * @param request  an {@link HttpServletRequest} object that
 *                 contains the request the client has made
 *                 of the servlet
 * @param response an {@link HttpServletResponse} object that
 *                 contains the response the servlet sends
 *                 to the client
 * @throws IOException      if an input or output error is
 *                          detected when the servlet handles
 *                          the request
 * @throws ServletException if the request for the POST
 *                          could not be handled
 * @see ServletOutputStream
 * @see ServletResponse#setContentType
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        final Subject subject = AuthenticationUtil.getSubject(request);

        if ((subject == null) || (subject.getPrincipals().isEmpty())) {
            processRequest(request, response);
        } else {
            Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    processRequest(request, response);
                    return null;
                }
            });
        }
    } catch (TransientException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.addHeader("Retry-After", Integer.toString(ex.getRetryDelay()));
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (JobPersistenceException ex) {
        // OutputStream not open, write an error response
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("failed to get or persist job state.");
        w.println("   reason: " + ex.getMessage());
        w.close();
    } catch (Throwable t) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain");
        PrintWriter w = response.getWriter();
        w.println("Unable to proceed with job execution.\n");
        w.println("Reason: " + t.getMessage());
        w.close();
    }
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();/*from   ww  w .  j a v  a  2 s .c o m*/
    addRemoteIpToLoggingContext(req);

    log.info("Handling autodiscover request...");

    byte[] reqBytes = null;
    reqBytes = ByteUtil.getContent(req.getInputStream(), req.getContentLength());
    if (reqBytes == null) {
        log.warn("No content found in the request");
        sendError(resp, 600, "No content found in the request");
        return;
    }
    String content = new String(reqBytes, "UTF-8");
    log.debug("Request before auth: %s", content);

    if (log.isDebugEnabled()) {
        Enumeration<String> enm = req.getHeaderNames();
        while (enm.hasMoreElements()) {
            String header = enm.nextElement();
            log.info("POST header: %s", header + ":" + req.getHeader(header));
        }
    }

    String email = null;
    String responseSchema = null;

    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new InputSource(new StringReader(content)));
        NodeList nList = doc.getElementsByTagName("Request");

        for (int i = 0; i < nList.getLength(); i++) {
            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                email = getTagValue("EMailAddress", element);
                responseSchema = getTagValue("AcceptableResponseSchema", element);

                if (email != null)
                    break;
            }
        }
    } catch (Exception e) {
        log.warn("cannot parse body: %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Body cannot be parsed");
        return;
    }

    //Return an error if there's no email address specified!
    if (email == null || email.length() == 0) {
        log.warn("No Email address is specified in the Request, %s", content);
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "No Email address is specified in the Request");
        return;
    }

    //Return an error if the response schema doesn't match ours!
    if (responseSchema != null && responseSchema.length() > 0) {

        if (!(responseSchema.equals(NS_MOBILE) || responseSchema.equals(NS_OUTLOOK))) {
            log.warn("Requested response schema not available " + responseSchema);
            sendError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    "Requested response schema not available " + responseSchema);
            return;
        }
    }

    log.debug("Authenticating user");
    Account acct = authenticate(req, resp, responseSchema);
    if (acct == null) {
        return;
    }
    log.debug("Authentication finished successfully");

    log.debug("content length: %d, content type: %s", req.getContentLength(), req.getContentType());
    if (req.getContentLength() == 0 || req.getContentType() == null) {
        log.warn("No suitable content found in the request");
        sendError(resp, 600, "No suitable content found in the request");
        return;
    }

    try {
        if (!(AccountUtil.addressMatchesAccount(acct, email) || acct.isAvailabilityServiceProvider())) { //Exchange server sends dummy email address from service account.
            log.warn(email + " doesn't match account addresses for user " + acct.getName());
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    email + " doesn't match account addresses");
            return;
        }
    } catch (ServiceException e) {
        log.warn("Account access error; user=" + acct.getName(), e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Account access error; user=" + acct.getName());
        return;
    }

    String respDoc = null;
    try {
        String serviceUrl = getServiceUrl(acct, responseSchema);
        String displayName = acct.getDisplayName() == null ? email : acct.getDisplayName();
        if (displayName.contains("@")) {
            displayName = displayName.substring(0, displayName.indexOf("@"));
        }
        log.debug("displayName: %s, email: %s, serviceUrl: %s", displayName, email, serviceUrl);
        if (isEwsClient(responseSchema)) {
            respDoc = createResponseDocForEws(displayName, email, serviceUrl, acct);
        } else {
            respDoc = createResponseDoc(displayName, email, serviceUrl);
        }
    } catch (Exception e) {
        log.warn(e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.info("Response: %s", respDoc);
    log.debug("response length: %d", respDoc.length());

    try {
        ByteUtil.copy(new ByteArrayInputStream(respDoc.getBytes("UTF-8")), true, resp.getOutputStream(), false);
    } catch (IOException e) {
        log.error("copy response error", e);
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }

    log.debug("setting content type to text/xml");
    resp.setContentType("text/xml");
    log.info("sending autodiscover response...");
}

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 ww  . j  a v a 2s .  co  m*/
    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();
}