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.apache.myfaces.renderkit.html.util.MyFacesResourceLoader.java

/**
 * Given a URI of form "{partial.class.name}/{resourceName}", locate the
 * specified file within the current classpath and write it to the
 * response object.//w ww  .ja  va 2  s.co  m
 * <p>
 * The partial class name has "org.apache.myfaces.custom." prepended
 * to it to form the fully qualified classname. This class object is
 * loaded, and Class.getResourceAsStream is called on it, passing
 * a uri of "resource/" + {resourceName}.
 * <p>
 * The data written to the response stream includes http headers
 * which define the mime content-type; this is deduced from the
 * filename suffix of the resource.
 * <p>
 * @see org.apache.myfaces.renderkit.html.util.ResourceLoader#serveResource(javax.servlet.ServletContext,
 *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
 */
public void serveResource(ServletContext context, HttpServletRequest request, HttpServletResponse response,
        String resourceUri) throws IOException {
    String[] uriParts = resourceUri.split("/", 2);

    String component = uriParts[0];
    if (component == null || component.trim().length() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
        log.error("Could not find parameter for component to load a resource.");
        return;
    }
    Class componentClass;
    String className = ORG_APACHE_MYFACES_CUSTOM + "." + component;
    try {
        componentClass = loadComponentClass(className);
    } catch (ClassNotFoundException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        log.error("Could not find the class for component " + className + " to load a resource.");
        return;
    }
    String resource = uriParts[1];
    if (resource == null || resource.trim().length() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No resource defined");
        log.error("No resource defined component class " + className);
        return;
    }

    InputStream is = null;

    try {
        ResourceProvider resourceProvider;
        if (ResourceProvider.class.isAssignableFrom(componentClass)) {
            try {
                resourceProvider = (ResourceProvider) componentClass.newInstance();
            } catch (InstantiationException e) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Unable to instantiate resource provider for resource " + resource + " for component "
                                + component);
                log.error("Unable to instantiate resource provider for resource " + resource + " for component "
                        + component, e);
                return;
            } catch (IllegalAccessException e) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Unable to instantiate resource provider for resource " + resource + " for component "
                                + component);
                log.error("Unable to instantiate resource provider for resource " + resource + " for component "
                        + component, e);
                return;
            }
        } else {
            resourceProvider = new DefaultResourceProvider(componentClass);
        }

        if (!resourceProvider.exists(context, resource)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Unable to find resource " + resource + " for component " + component
                            + ". Check that this file is available " + "in the classpath in sub-directory "
                            + "/resource of the package-directory.");
            log.error("Unable to find resource " + resource + " for component " + component
                    + ". Check that this file is available " + "in the classpath in sub-directory "
                    + "/resource of the package-directory.");
        } else {
            // URLConnection con = url.openConnection();

            long lastModified = resourceProvider.getLastModified(context, resource);
            if (lastModified < 1) {
                // fallback
                lastModified = getLastModified();
            }

            long browserDate = request.getDateHeader("If-Modified-Since");
            if (browserDate > -1) {
                // normalize to seconds - this should work with any os
                lastModified = (lastModified / 1000) * 1000;
                browserDate = (browserDate / 1000) * 1000;

                if (lastModified == browserDate) {
                    // the browser already has the correct version

                    response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
                    return;
                }
            }

            int contentLength = resourceProvider.getContentLength(context, resource);
            String contentEncoding = resourceProvider.getEncoding(context, resource);

            is = resourceProvider.getInputStream(context, resource);

            defineContentHeaders(request, response, resource, contentLength, contentEncoding);
            defineCaching(request, response, resource, lastModified);
            writeResource(request, response, is);
        }
    } finally {
        // nothing to do here..
    }
}

From source file:org.opencastproject.inspection.impl.endpoints.MediaInspectionRestEndpoint.java

@POST
@Produces(MediaType.TEXT_XML)/*from   ww  w. ja v a  2 s .  co  m*/
@Path("enrich")
@RestQuery(name = "enrich", description = "Analyze and add missing metadata of a given media file, returning a receipt to check on the status and outcome of the job.", restParameters = {
        @RestParameter(description = "MediaPackage Element, that should be enriched with metadata ", isRequired = true, name = "mediaPackageElement", type = RestParameter.Type.TEXT),
        @RestParameter(description = "Should the existing metadata values remain", isRequired = true, name = "override", type = RestParameter.Type.BOOLEAN) }, reponses = {
                @RestResponse(description = "XML encoded receipt is returned.", responseCode = HttpServletResponse.SC_NO_CONTENT),
                @RestResponse(description = "Service unavailabe or not currently present", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE),
                @RestResponse(description = "Problem retrieving media file or invalid media file or URL.", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "")
public Response enrichTrack(@FormParam("mediaPackageElement") String mediaPackageElement,
        @FormParam("override") boolean override) {
    checkNotNull(service);
    try {
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(IOUtils.toInputStream(mediaPackageElement, "UTF-8"));
        MediaPackageElement mpe = MediaPackageElementBuilderFactory.newInstance().newElementBuilder()
                .elementFromManifest(doc.getDocumentElement(), new DefaultMediaPackageSerializerImpl());
        Job job = service.enrich(mpe, override);
        return Response.ok(new JaxbJob(job)).build();
    } catch (Exception e) {
        logger.info(e.getMessage(), e);
        return Response.serverError().build();
    }
}

From source file:nl.surfnet.mujina.saml.SSOSuccessAuthnResponder.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AuthnRequestInfo info = (AuthnRequestInfo) request.getSession()
            .getAttribute(AuthnRequestInfo.class.getName());

    if (info == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from   w  ww .  j  a  v a  2  s . c  o  m
    }

    logger.debug("AuthnRequestInfo: {}", info);

    SimpleAuthentication authToken = (SimpleAuthentication) SecurityContextHolder.getContext()
            .getAuthentication();
    DateTime authnInstant = new DateTime(request.getSession().getCreationTime());

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID()));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    Credential signingCredential = null;
    try {
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (org.opensaml.xml.security.SecurityException e) {
        logger.warn("Unable to resolve EntityID while signing", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Validate.notNull(signingCredential);

    AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(signingCredential,
            idpConfiguration.getEntityID(), timeService, idService, idpConfiguration);
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String remoteIP = request.getRemoteAddr();
    String attributeJson = null;

    if (null != request.getCookies()) {
        for (Cookie current : request.getCookies()) {
            if (current.getName().equalsIgnoreCase("mujina-attr")) {
                logger.info("Found a attribute cookie, this is used for the assertion response");
                attributeJson = URLDecoder.decode(current.getValue(), "UTF-8");
            }
        }
    }
    String acsEndpointURL = info.getAssertionConsumerURL();
    if (idpConfiguration.getAcsEndpoint() != null) {
        acsEndpointURL = idpConfiguration.getAcsEndpoint().getUrl();
    }
    Response authResponse = authnResponseGenerator.generateAuthnResponse(remoteIP, authToken, acsEndpointURL,
            responseValidityTimeInSeconds, info.getAuthnRequestID(), authnInstant, attributeJson,
            info.getEntityId());
    Endpoint endpoint = endpointGenerator.generateEndpoint(
            org.opensaml.saml2.metadata.AssertionConsumerService.DEFAULT_ELEMENT_NAME, acsEndpointURL, null);

    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

    String relayState = request.getParameter("RelayState");

    //we could use a different adapter to send the response based on request issuer...
    try {
        adapter.sendSAMLMessage(authResponse, endpoint, response, relayState, signingCredential);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.access.WikiAccessServlet.java

/**
 * handle get and post communication from the user
 * /*w w  w  . j a  v  a 2s .  c om*/
 * @param req
 *        HttpServletRequest object with the client request
 * @param res
 *        HttpServletResponse object back to the client
 */
public void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    long start = System.currentTimeMillis();

    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // get the path info
    String path = req.getPathInfo();
    req.setAttribute(Tool.NATIVE_URL, null);
    if (path == null)
        path = "";

    // pre-process the path
    String origPath = path;
    path = preProcessPath(path, req);

    // what is being requested?
    Reference ref = EntityManager.newReference(path);

    // let the entity producer handle it
    try {
        // make sure we have a valid reference with an entity producer we can talk to
        EntityProducer service = ref.getEntityProducer();
        if (service == null)
            throw new EntityNotDefinedException(ref.getReference());

        // get the producer's HttpAccess helper, it might not support one
        HttpAccess access = service.getHttpAccess();
        if (access == null)
            throw new EntityNotDefinedException(ref.getReference());

        // let the helper do the work
        access.handleAccess(req, res, ref, null);
    } catch (EntityNotDefinedException e) {
        // the request was not valid in some way
        sendError(res, HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (EntityPermissionException e) {
        // the end user does not have permission - offer a login if there is no user id yet established
        // if not permitted, and the user is the anon user, let them login
        if (SessionManager.getCurrentSessionUserId() == null) {
            try {
                doLogin(req, res, origPath);
            } catch (IOException ioex) {
            }
            return;
        }

        // otherwise reject the request
        sendError(res, HttpServletResponse.SC_FORBIDDEN);
    } catch (EntityAccessOverloadException e) {
        M_log.info("dispatch(): ref: " + ref.getReference() + e);
        sendError(res, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } catch (Throwable e) {
        M_log.warn("dispatch(): exception: ", e);
        sendError(res, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    finally {
        long end = System.currentTimeMillis();

        // log
        if (M_log.isDebugEnabled())
            M_log.debug("from:" + req.getRemoteAddr() + " path:" + origPath + " options: "
                    + req.getQueryString() + " time: " + (end - start));
    }
}

From source file:org.apache.catalina.core.StandardWrapperValve.java

/**
 * Invoke the servlet we are managing, respecting the rules regarding
 * servlet lifecycle and SingleThreadModel support.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 * @param valveContext Valve context used to forward to the next Valve
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 *//*  ww w.j a va2s .  c o m*/
public final void invoke(Request request, Response response, ValveContext valveContext)
        throws IOException, ServletException {

    // Initialize local variables we may need
    boolean unavailable = false;
    Throwable throwable = null;
    // This should be a Request attribute...
    long t1 = System.currentTimeMillis();
    requestCount++;
    StandardWrapper wrapper = (StandardWrapper) getContainer();
    HttpRequest hrequest = (HttpRequest) request;
    Servlet servlet = null;
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();

    // Check for the application being marked unavailable
    if (!((Context) wrapper.getParent()).getAvailable()) {
        hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                sm.getString("standardContext.isUnavailable"));
        unavailable = true;
    }

    // Check for the servlet being marked unavailable
    if (!unavailable && wrapper.isUnavailable()) {
        log(sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        if (hres == null) {
            ; // NOTE - Not much we can do generically
        } else {
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < Long.MAX_VALUE)) {
                hres.setDateHeader("Retry-After", available);
                hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
            } else if (available == Long.MAX_VALUE) {
                hres.sendError(HttpServletResponse.SC_NOT_FOUND,
                        sm.getString("standardWrapper.notFound", wrapper.getName()));
            }
        }
        unavailable = true;
    }

    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (UnavailableException e) {
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            hres.setDateHeader("Retry-After", available);
            hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            hres.sendError(HttpServletResponse.SC_NOT_FOUND,
                    sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    } catch (ServletException e) {
        log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    } catch (Throwable e) {
        log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }

    // Acknowlege the request
    try {
        response.sendAcknowledgement();
    } catch (IOException e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    MessageBytes requestPathMB = null;
    if (hreq != null) {
        requestPathMB = hrequest.getRequestPathMB();
    }
    hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, ApplicationFilterFactory.REQUEST_INTEGER);
    hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB);
    // Create the filter chain for this request
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain((ServletRequest) request, wrapper, servlet);

    // Call the filter chain for this request
    // NOTE: This also calls the servlet's service() method
    try {
        String jspFile = wrapper.getJspFile();
        if (jspFile != null)
            hreq.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
        else
            hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(hreq, hres);
        }
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
    } catch (ClientAbortException e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        throwable = e;
        exception(request, response, e);
    } catch (IOException e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
    } catch (UnavailableException e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e);
        //            throwable = e;
        //            exception(request, response, e);
        wrapper.unavailable(e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            hres.setDateHeader("Retry-After", available);
            hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                    sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            hres.sendError(HttpServletResponse.SC_NOT_FOUND,
                    sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
        // Do not save exception in 'throwable', because we
        // do not want to do exception(request, response, e) processing
    } catch (ServletException e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        Throwable rootCause = e;
        Throwable rootCauseCheck = null;

        // Extra aggressive rootCause finding
        do {
            try {
                rootCauseCheck = (Throwable) PropertyUtils.getProperty(rootCause, "rootCause");
                if (rootCauseCheck != null)
                    rootCause = rootCauseCheck;

            } catch (ClassCastException ex) {
                rootCauseCheck = null;
            } catch (IllegalAccessException ex) {
                rootCauseCheck = null;
            } catch (NoSuchMethodException ex) {
                rootCauseCheck = null;
            } catch (java.lang.reflect.InvocationTargetException ex) {
                rootCauseCheck = null;
            }
        } while (rootCauseCheck != null);

        if (!(rootCause instanceof ClientAbortException)) {
            log(sm.getString("standardWrapper.serviceException", wrapper.getName()), rootCause);
        }
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        hreq.removeAttribute(Globals.JSP_FILE_ATTR);
        log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
    }

    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        log(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }

    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (Throwable e) {
        log(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }

    // If this servlet has been marked permanently unavailable,
    // unload it and release this instance
    try {
        if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) {
            wrapper.unload();
        }
    } catch (Throwable e) {
        log(sm.getString("standardWrapper.unloadException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    long t2 = System.currentTimeMillis();

    long time = t2 - t1;
    processingTime += time;
    if (time > maxTime)
        maxTime = time;
    if (time < minTime)
        minTime = time;

}

From source file:org.codice.ddf.security.filter.websso.WebSSOFilter.java

private void handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        FilterChain filterChain, List<AuthenticationHandler> handlers) throws IOException, ServletException {

    if (handlers.size() == 0) {
        LOGGER.warn("Handlers not ready. Returning status code 503, Service Unavailable.");
        returnSimpleResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, httpResponse);
        return;//from   w ww  .  j a  v a  2 s.c  om
    }

    // First pass, see if anyone can come up with proper security token from the get-go
    HandlerResult result = null;
    LOGGER.debug("Checking for existing tokens in request.");

    for (AuthenticationHandler auth : handlers) {
        result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, false);
        if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(),
                    result.getStatus());
            break;
        }
    }

    // If we haven't received usable credentials yet, go get some
    if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
        LOGGER.debug("First pass with no tokens found - requesting tokens");
        // This pass, tell each handler to do whatever it takes to get a SecurityToken
        for (AuthenticationHandler auth : handlers) {
            result = auth.getNormalizedToken(httpRequest, httpResponse, filterChain, true);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the result status to {}", auth.getAuthenticationType(),
                        result.getStatus());
                break;
            }
        }
    }

    String path = StringUtils.isNotBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
            : httpRequest.getServletPath() + StringUtils.defaultString(httpRequest.getPathInfo());
    String ipAddress = httpRequest.getHeader("X-FORWARDED-FOR");

    if (ipAddress == null) {
        ipAddress = httpRequest.getRemoteAddr();
    }

    if (result != null) {
        switch (result.getStatus()) {
        case REDIRECTED:
            // handler handled the response - it is redirecting or whatever
            // necessary to get their tokens
            LOGGER.debug("Stopping filter chain - handled by plugins");
            return;
        case NO_ACTION:
            // should never occur - one of the handlers should have returned a token
            LOGGER.warn(
                    "No handlers were able to determine required credentials, returning bad request to {}. Check policy configuration for path: {}",
                    ipAddress, path);
            returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
            return;
        case COMPLETED:
            if (result.getToken() == null) {
                LOGGER.warn(
                        "Completed without credentials for {} - check context policy configuration for path: {}",
                        ipAddress, path);
                returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
                return;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "Attaching result handler to the http request - token is instance of {} from classloader {}",
                        result.getToken().getClass().getName(), result.getToken().getClass().getClassLoader());
            }
            httpRequest.setAttribute(DDF_AUTHENTICATION_TOKEN, result);
            break;
        default:
            LOGGER.warn("Unexpected response from handler - ignoring. Remote IP: {}, Path: {}", ipAddress,
                    path);
            return;
        }
    } else {
        LOGGER.warn(
                "Expected login credentials from {} - didn't find any. Returning a bad request for path: {}",
                ipAddress, path);
        returnSimpleResponse(HttpServletResponse.SC_BAD_REQUEST, httpResponse);
        return;
    }

    // If we got here, we've received our tokens to continue
    LOGGER.debug("Invoking the rest of the filter chain");
    try {
        filterChain.doFilter(httpRequest, httpResponse);
    } catch (InvalidSAMLReceivedException e) {
        // we tried to process an invalid or missing SAML assertion
        returnSimpleResponse(HttpServletResponse.SC_UNAUTHORIZED, httpResponse);
    } catch (Exception e) {
        LOGGER.debug("Exception in filter chain - passing off to handlers. Msg: {}", e.getMessage(), e);

        // First pass, see if anyone can come up with proper security token
        // from the git-go
        result = null;
        for (AuthenticationHandler auth : handlers) {
            result = auth.handleError(httpRequest, httpResponse, filterChain);
            if (result.getStatus() != HandlerResult.Status.NO_ACTION) {
                LOGGER.debug("Handler {} set the status to {}", auth.getAuthenticationType(),
                        result.getStatus());
                break;
            }
        }
        if (result == null || result.getStatus() == HandlerResult.Status.NO_ACTION) {
            LOGGER.debug("Error during authentication - no error recovery attempted - returning bad request.");
            httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            httpResponse.flushBuffer();
        }
    }
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void deleteTweets(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userToken = request.getParameter("u");
    String userSecret = request.getParameter("s");
    long statusID = Long.parseLong(request.getParameter("d"));

    log.debug("Deleting tweet " + statusID);

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/* w ww . j a v a 2s.co  m*/
    }

    try {
        Status s = twitter.destroyStatus(statusID);
        if (s != null) {
            // success
            response.setStatus(HttpServletResponse.SC_OK);

            // remove tweets from cache
            String cacheKey = userToken;
            tweetsCache.remove(cacheKey);

        } else {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }

    } catch (TwitterException e) {
        // problem in deleting the tweet
        log.error("Delete Tweet: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage());
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:org.apache.hadoop.mapred.TestHAWebUI.java

@Test
public void redirectLoop() throws Exception {
    testRedirect(JobTrackerHAHttpRedirector.RedirectorServlet.class,
            JobTrackerHAHttpRedirector.RedirectorServlet.class, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}

From source file:org.hippoecm.repository.PingServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int resultStatus = HttpServletResponse.SC_OK;
    String resultMessage = getOkMessage();
    Exception exception = null;/*from  w w  w.  j  av  a 2 s. co m*/

    if (hasCustomMessage()) {
        resultMessage = "CUSTOM - " + customMessage;
        resultStatus = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        printMessage(response, resultMessage, resultStatus, exception);
        return;
    }

    try {
        doRepositoryChecks();
    } catch (PingException e) {
        resultStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        resultMessage = e.getMessage();
        exception = e;
    } catch (RuntimeException e) {
        resultStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        resultMessage = "FAILURE - Serious problem with the ping servlet. Might have lost repository access: "
                + e.getClass().getName() + ": " + e.getMessage();
        exception = e;
    } finally {
        printMessage(response, resultMessage, resultStatus, exception);
        closeHttpSession(request);
    }
}

From source file:org.opencastproject.capture.admin.endpoint.CaptureAgentStateRestService.java

@POST
@Produces(MediaType.TEXT_HTML)/* ww  w . j  a va 2  s  .  co m*/
@Path("agents/{name}")
// Todo: Capture agent may send an optional FormParam containing it's configured address.
// If this exists don't use request.getRemoteHost() for the URL
@RestQuery(name = "setAgentState", description = "Set the status of a given capture agent", pathParameters = {
        @RestParameter(name = "name", description = "The name of a given capture agent", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = {
                @RestParameter(description = "The address of a given capture agent", isRequired = true, name = "address", type = Type.STRING),
                @RestParameter(description = "The state of the capture agent", isRequired = true, name = "state", type = Type.STRING) }, reponses = {
                        @RestResponse(description = "{agentName} set to {state}", responseCode = HttpServletResponse.SC_OK),
                        @RestResponse(description = "{state} is empty or not known", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                        @RestResponse(description = "The agent {agentName} does not exist", responseCode = HttpServletResponse.SC_NOT_FOUND),
                        @RestResponse(description = "If no capture agent state service is available", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response setAgentState(@Context HttpServletRequest request, @FormParam("address") String address,
        @PathParam("name") String agentName, @FormParam("state") String state) throws NotFoundException {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();

    if (StringUtils.isBlank(state) || !AgentState.KNOWN_STATES.contains(state)) {
        logger.debug("'{}' is not a valid state", state);
        return Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build();
    }

    if (StringUtils.isEmpty(address))
        address = request.getRemoteHost();

    logger.debug("Agents URL: {}", address);

    boolean agentStateUpdated = service.setAgentState(agentName, state);
    boolean agentUrlUpdated = service.setAgentUrl(agentName, address);

    if (!agentStateUpdated && !agentUrlUpdated) {
        logger.debug("{}'s state '{}' and url '{}' has not changed, nothing has been updated",
                new String[] { agentName, state, address });
        return Response.ok().build();
    }
    logger.debug("{}'s state successfully set to {}", agentName, state);
    return Response.ok(agentName + " set to " + state).build();
}