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.osaf.cosmo.mc.MorseCodeServlet.java

/**
 * Handles publish requests./* www.ja  v  a 2  s.c  o  m*/
 */
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling PUT for " + req.getPathInfo());

    CollectionPath cp = CollectionPath.parse(req.getPathInfo());
    if (cp != null) {
        String parentUid = req.getParameter(PARAM_PARENT_UID);
        if (StringUtils.isEmpty(parentUid))
            parentUid = null;
        EimmlStreamReader reader = null;
        try {
            if (!checkWritePreconditions(req, resp))
                return;

            reader = new EimmlStreamReader(req.getReader());
            if (!reader.getCollectionUuid().equals(cp.getUid())) {

                String msg = "EIMML collection uid " + reader.getCollectionUuid()
                        + " does not match target collection uid " + cp.getUid();
                handleGeneralException(new BadRequestException(msg), resp);
                return;
            }

            EimmlStreamReaderIterator i = new EimmlStreamReaderIterator(reader);
            PubRecords records = new PubRecords(i, reader.getCollectionName(), reader.getCollectionHue());

            Set<TicketType> ticketTypes = null;
            try {
                ticketTypes = parseTicketTypes(req);
            } catch (IllegalArgumentException e) {
                handleGeneralException(new BadRequestException(e), resp);
                return;
            }

            PubCollection pubCollection = controller.publishCollection(cp.getUid(), parentUid, records,
                    ticketTypes);

            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.addHeader(HEADER_SYNC_TOKEN, pubCollection.getToken().serialize());
            for (Ticket ticket : pubCollection.getCollection().getTickets())
                resp.addHeader(HEADER_TICKET, formatTicket(ticket));

            return;
        } catch (CosmoSecurityException e) {
            if (e instanceof ItemSecurityException) {
                InsufficientPrivilegesException ipe = new InsufficientPrivilegesException(
                        (ItemSecurityException) e);
                handleGeneralException(ipe, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
            }
            return;
        } catch (IllegalArgumentException e) {
            String msg = "Parent uid must be specified when authenticated principal is not a user";
            handleGeneralException(new BadRequestException(msg), resp);
            return;
        } catch (EimmlStreamException e) {
            Throwable cause = e.getCause();
            String msg = "Unable to read EIM stream: " + e.getMessage();
            msg += cause != null ? ": " + cause.getMessage() : "";
            handleGeneralException(new BadRequestException(msg, e), resp);
            return;
        } catch (UidInUseException e) {
            handleGeneralException(new MorseCodeException(HttpServletResponse.SC_CONFLICT, e), resp);
            return;
        } catch (ServerBusyException e) {
            log.debug("received ServerBusyException during PUT");
            resp.setIntHeader(HEADER_RETRY_AFTER, 5);
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The server was busy, try again later");
            return;
        } catch (MorseCodeException e) {
            Throwable root = e.getCause();
            if (root != null && root instanceof EimmlStreamException) {
                String msg = "Unable to read EIM stream: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            if (root != null && root instanceof EimSchemaException) {
                String msg = "Unable to process EIM records: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            handleGeneralException(e, resp);
            return;
        } catch (RuntimeException e) {
            handleGeneralException(new MorseCodeException(e), resp);
            return;
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

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

/**
 * Creates a new <tt>Conference</tt> in (the associated)
 * <tt>Videobridge</tt>./*  w  w w .j  av a2s .co m*/
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPostConferencesJSON(Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (RESTUtil.isJSONContentType(request.getContentType())) {
        Object requestJSONObject = null;
        int status = 0;

        try {
            requestJSONObject = new JSONParser().parse(request.getReader());
            if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
        } catch (ParseException pe) {
            status = HttpServletResponse.SC_BAD_REQUEST;
        }
        if (status == 0) {
            ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                    .deserializeConference((JSONObject) requestJSONObject);

            if ((requestConferenceIQ == null) || (requestConferenceIQ.getID() != null)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            } else {
                ColibriConferenceIQ responseConferenceIQ = null;

                try {
                    IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                            Videobridge.OPTION_ALLOW_NO_FOCUS);

                    if (responseIQ instanceof ColibriConferenceIQ) {
                        responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                    } else {
                        status = getHttpStatusCodeForResultIq(responseIQ);
                    }
                } catch (Exception e) {
                    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
                if (status == 0 && responseConferenceIQ != null) {
                    JSONObject responseJSONObject = JSONSerializer.serializeConference(responseConferenceIQ);

                    if (responseJSONObject == null)
                        responseJSONObject = new JSONObject();

                    response.setStatus(HttpServletResponse.SC_OK);
                    responseJSONObject.writeJSONString(response.getWriter());
                }
            }
        }
        if (status != 0)
            response.setStatus(status);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    }
}

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

@DELETE
@Path("recordings/{id}")
@RestQuery(name = "removeRecording", description = "Remove record of a given recording", pathParameters = {
        @RestParameter(description = "The ID of a given recording", isRequired = true, name = "id", type = Type.STRING) }, restParameters = {}, reponses = {
                @RestResponse(description = "{id} removed", responseCode = HttpServletResponse.SC_OK),
                @RestResponse(description = "{id} is empty", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                @RestResponse(description = "Recording with {id} could not be found", responseCode = HttpServletResponse.SC_NOT_FOUND),
                @RestResponse(description = "If no capture agent state service is available", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response removeRecording(@PathParam("id") String id) throws NotFoundException {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();

    if (StringUtils.isEmpty(id))
        return Response.serverError().status(Response.Status.BAD_REQUEST).build();

    service.removeRecording(id);/*from   w  w  w.  j  ava 2s.  c o m*/
    return Response.ok(id + " removed").build();
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

private synchronized void initializeServer(final ProcessContext context) throws Exception {
    if (initialized.get()) {
        return;/*from  www  .  j  a v  a 2  s. co m*/
    }
    this.containerQueue = new LinkedBlockingQueue<>(context.getProperty(CONTAINER_QUEUE_SIZE).asInteger());
    final String host = context.getProperty(HOSTNAME).getValue();
    final int port = context.getProperty(PORT).asInteger();
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT)
            .asControllerService(SSLContextService.class);

    final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
    final boolean need;
    final boolean want;
    if (CLIENT_NEED.equals(clientAuthValue)) {
        need = true;
        want = false;
    } else if (CLIENT_WANT.equals(clientAuthValue)) {
        need = false;
        want = true;
    } else {
        need = false;
        want = false;
    }

    final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want);
    final Server server = new Server(port);

    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    if (sslFactory == null) {
        // create the connector
        final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            http.setHost(host);
        }
        http.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { http });
    } else {
        // add some secure config
        final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
        httpsConfiguration.setSecureScheme("https");
        httpsConfiguration.setSecurePort(port);
        httpsConfiguration.addCustomizer(new SecureRequestCustomizer());

        // build the connector
        final ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslFactory, "http/1.1"),
                new HttpConnectionFactory(httpsConfiguration));

        // set host and port
        if (StringUtils.isNotBlank(host)) {
            https.setHost(host);
        }
        https.setPort(port);

        // add this connector
        server.setConnectors(new Connector[] { https });
    }

    final Set<String> allowedMethods = new HashSet<>();
    if (context.getProperty(ALLOW_GET).asBoolean()) {
        allowedMethods.add("GET");
    }
    if (context.getProperty(ALLOW_POST).asBoolean()) {
        allowedMethods.add("POST");
    }
    if (context.getProperty(ALLOW_PUT).asBoolean()) {
        allowedMethods.add("PUT");
    }
    if (context.getProperty(ALLOW_DELETE).asBoolean()) {
        allowedMethods.add("DELETE");
    }
    if (context.getProperty(ALLOW_HEAD).asBoolean()) {
        allowedMethods.add("HEAD");
    }
    if (context.getProperty(ALLOW_OPTIONS).asBoolean()) {
        allowedMethods.add("OPTIONS");
    }

    final String additionalMethods = context.getProperty(ADDITIONAL_METHODS).getValue();
    if (additionalMethods != null) {
        for (final String additionalMethod : additionalMethods.split(",")) {
            final String trimmed = additionalMethod.trim();
            if (!trimmed.isEmpty()) {
                allowedMethods.add(trimmed.toUpperCase());
            }
        }
    }

    final String pathRegex = context.getProperty(PATH_REGEX).getValue();
    final Pattern pathPattern = (pathRegex == null) ? null : Pattern.compile(pathRegex);

    server.setHandler(new AbstractHandler() {
        @Override
        public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
                final HttpServletResponse response) throws IOException, ServletException {

            final String requestUri = request.getRequestURI();
            if (!allowedMethods.contains(request.getMethod().toUpperCase())) {
                getLogger().info(
                        "Sending back METHOD_NOT_ALLOWED response to {}; method was {}; request URI was {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                response.sendError(Status.METHOD_NOT_ALLOWED.getStatusCode());
                return;
            }

            if (pathPattern != null) {
                final URI uri;
                try {
                    uri = new URI(requestUri);
                } catch (final URISyntaxException e) {
                    throw new ServletException(e);
                }

                if (!pathPattern.matcher(uri.getPath()).matches()) {
                    response.sendError(Status.NOT_FOUND.getStatusCode());
                    getLogger().info("Sending back NOT_FOUND response to {}; request was {} {}",
                            new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri });
                    return;
                }
            }

            // If destination queues full, send back a 503: Service Unavailable.
            if (context.getAvailableRelationships().isEmpty()) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                return;
            }

            // Right now, that information, though, is only in the ProcessSession, not the ProcessContext,
            // so it is not known to us. Should see if it can be added to the ProcessContext.
            final AsyncContext async = baseRequest.startAsync();
            async.setTimeout(Long.MAX_VALUE); // timeout is handled by HttpContextMap
            final boolean added = containerQueue.offer(new HttpRequestContainer(request, response, async));

            if (added) {
                getLogger().debug("Added Http Request to queue for {} {} from {}",
                        new Object[] { request.getMethod(), requestUri, request.getRemoteAddr() });
            } else {
                getLogger().info("Sending back a SERVICE_UNAVAILABLE response to {}; request was {} {}",
                        new Object[] { request.getRemoteAddr(), request.getMethod(), request.getRemoteAddr() });

                response.sendError(Status.SERVICE_UNAVAILABLE.getStatusCode());
                response.flushBuffer();
                async.complete();
            }
        }
    });

    this.server = server;
    server.start();

    getLogger().info("Server started and listening on port " + getPort());

    initialized.set(true);
}

From source file:org.b3log.rhythm.processor.ArticleProcessor.java

/**
 * Gets articles by tags./*from  w  w w.  j  ava2s  . com*/
 *
 * @param context the specified context
 * @throws IOException io exception
 */
@RequestProcessing(value = "/get-articles-by-tags.do", method = HTTPRequestMethod.GET)
public void getArticlesByTags(final HTTPRequestContext context) throws IOException {
    final HttpServletRequest request = context.getRequest();
    final String tagParam = request.getParameter(Tag.TAGS);
    if (Strings.isEmptyOrNull(tagParam)) {
        context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    final String tagString = tagParam.toLowerCase();
    String soloHost = request.getParameter(Blog.BLOG_HOST);
    if (Strings.isEmptyOrNull(soloHost)) {
        context.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (soloHost.contains("://")) {
        soloHost = StringUtils.substringAfter(soloHost, "://");
    }

    soloHost = soloHost.split(":")[0];

    final int pageSize = Integer.valueOf(request.getParameter(Pagination.PAGINATION_PAGE_SIZE));
    String callbackFuncName = request.getParameter("callback");
    if (Strings.isEmptyOrNull(callbackFuncName)) {
        callbackFuncName = "callback";
    }

    final JSONObject jsonObject = new JSONObject();

    final JSONRenderer renderer = new JSONRenderer();
    renderer.setCallback(callbackFuncName); // Sets JSONP
    context.setRenderer(renderer);
    renderer.setJSONObject(jsonObject);

    jsonObject.put(Keys.STATUS_CODE, StatusCodes.GET_ARTICLES_SUCC);

    final List<JSONObject> articles = new ArrayList<JSONObject>();

    LOGGER.log(Level.DEBUG, "Getting articles by tags[{0}]....", tagString);
    try {
        final String[] tags = tagString.split(",");

        for (int i = 0; i < tags.length; i++) {
            final String tagTitle = tags[i];
            final JSONObject tag = tagRepository.getByTitle(tagTitle);

            if (null != tag) {
                LOGGER.log(Level.DEBUG, "Tag Title[{0}]", tag.getString(Tag.TAG_TITLE_LOWER_CASE));

                final String tagId = tag.getString(Keys.OBJECT_ID);
                final JSONObject result = tagArticleRepository.getByTagId(tagId, 1, pageSize);
                final JSONArray tagArticleRelations = result.getJSONArray(Keys.RESULTS);
                final int relationSize = pageSize < tagArticleRelations.length() ? pageSize
                        : tagArticleRelations.length();
                LOGGER.log(Level.TRACE, "Relation size[{0}]", relationSize);

                for (int j = 0; j < relationSize; j++) {
                    final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(j);
                    LOGGER.log(Level.TRACE, "Relation[{0}]", tagArticleRelation.toString());
                    final String relatedArticleId = tagArticleRelation
                            .getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
                    final JSONObject article = articleRepository.get(relatedArticleId);

                    String articleHost = article.getString(Blog.BLOG_HOST);
                    if (articleHost.contains("://")) {
                        articleHost = StringUtils.substringAfter(articleHost, "://");
                    }

                    articleHost = articleHost.split(":")[0];

                    if (articleHost.equalsIgnoreCase(soloHost)) {
                        continue; // Excludes articles from requested host
                    }

                    boolean existed = false;
                    for (final JSONObject relevantArticle : articles) {
                        if (relevantArticle.getString(Keys.OBJECT_ID)
                                .equals(article.getString(Keys.OBJECT_ID))) {
                            existed = true;
                        }
                    }

                    if (!existed) {
                        articles.add(article);
                    }

                    if (articles.size() == pageSize) {
                        break; // Got enough
                    }
                }
            }

            if (articles.size() == pageSize) {
                break; // Got enough
            }
        }

        removeUnusedProperties(articles);

        jsonObject.put(Article.ARTICLES, articles);

        jsonObject.put(Keys.STATUS_CODE, StatusCodes.GET_ARTICLES_SUCC);

        LOGGER.log(Level.DEBUG, "Got articles[{0}] by tag[{1}]", new Object[] { articles, tagString });
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Can not get articles", e);

        try {
            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:hello.MyPostHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder// www  . ja va2 s.  co  m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    final ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    final SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            client = clientBuilder.build();
        }

        bytesToSend += flowFile.getSize();
        break;
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;

    String userName = "Chris";
    String password = "password";
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("userName", userName);
    builder.addTextBody("password", password);
    for (final FlowFile flowFile : flowFileList) {
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream rawIn) throws IOException {
                InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(rawIn));
                builder.addBinaryBody("file", in, ContentType.DEFAULT_BINARY, "filename");
            }
        });
    }

    final HttpEntity entity2 = builder.build();

    post.setEntity(entity2);
    post.setConfig(requestConfig);

    final String contentType;

    contentType = DEFAULT_CONTENT_TYPE;
    post.setHeader(CONTENT_TYPE_HEADER, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (final IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, "
                                + "since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (final FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

protected void processAggregatorRequest(HttpServletRequest req, HttpServletResponse resp) {
    final String sourceMethod = "processAggregatorRequest"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp });
    }/*from   w w w . j ava  2 s  .c o m*/
    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                try {
                    // try to get platform URI from IResource in case uri specifies
                    // aggregator specific scheme like namedbundleresource
                    configUri = newResource(configUri).getURI();
                } catch (UnsupportedOperationException e) {
                    // Not fatal.  Just use uri as specified.
                }
                lastModified = configUri.toURL().openConnection().getLastModified();
            }
            if (lastModified > getConfig().lastModified()) {
                if (reloadConfig()) {
                    // If the config has been modified, then dependencies will be revalidated
                    // asynchronously.  Rather than forcing the current request to wait, return
                    // a response that will display an alert informing the user of what is
                    // happening and asking them to reload the page.
                    String content = "alert('" + //$NON-NLS-1$
                            StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$
                    resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
                    CopyUtil.copy(new StringReader(content), resp.getOutputStream());
                    return;
                }
            }
        }

        getTransport().decorateRequest(req);
        notifyRequestListeners(RequestNotifierAction.start, req, resp);

        ILayer layer = getLayer(req);
        long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req))
                / 1000) * 1000;
        if (modifiedSince >= lastModified) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
                        getName() + ":" //$NON-NLS-1$
                        + req.getAttribute(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME).toString());
            }
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            // Get the InputStream for the response.  This call sets the Content-Type,
            // Content-Length and Content-Encoding headers in the response.
            InputStream in = layer.getInputStream(req, resp);
            // if any of the readers included an error response, then don't cache the layer.
            if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
                resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
                int expires = getConfig().getExpires();
                resp.addHeader("Cache-Control", //$NON-NLS-1$
                        "public" + (expires > 0 ? (", max-age=" + expires) : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                );
            }
            CopyUtil.copy(in, resp.getOutputStream());
        }
        notifyRequestListeners(RequestNotifierAction.end, req, resp);
    } catch (DependencyVerificationException e) {
        // clear the cache now even though it will be cleared when validateDeps has
        // finished (asynchronously) so that any new requests will be forced to wait
        // until dependencies have been validated.
        getCacheManager().clearCache();
        getDependencies().validateDeps(false);

        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed,
                    new Object[] { e.getMessage(), "aggregator " + //$NON-NLS-1$
                            "validatedeps " + //$NON-NLS-1$
                            getName() + " clean", //$NON-NLS-1$
                            getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    }));
            String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (ProcessingDependenciesException e) {
        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (BadRequestException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (NotFoundException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        concurrentMap.clear();
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

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

private void doPostShutdownJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/*from w w w . j  a  va 2s . c om*/
    }

    if (!RESTUtil.isJSONContentType(request.getContentType())) {
        response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        return;
    }

    Object requestJSONObject;
    int status;

    try {
        requestJSONObject = new JSONParser().parse(request.getReader());
        if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    } catch (ParseException pe) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    ShutdownIQ requestShutdownIQ = JSONDeserializer.deserializeShutdownIQ((JSONObject) requestJSONObject);

    if ((requestShutdownIQ == null)) {
        status = HttpServletResponse.SC_BAD_REQUEST;
    } else {
        // Fill source address
        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }

        requestShutdownIQ.setFrom(ipAddress);

        try {
            IQ responseIQ = videobridge.handleShutdownIQ(requestShutdownIQ);

            if (IQ.Type.RESULT.equals(responseIQ.getType())) {
                status = HttpServletResponse.SC_OK;
            } else {
                status = getHttpStatusCodeForResultIq(responseIQ);
            }
        } catch (Exception e) {
            logger.error("Error while trying to handle shutdown request", e);
            status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    }
    response.setStatus(status);
}

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

/**
 * Ask the resource represented by this RequestDispatcher to process
 * the associated request, and create (or append to) the associated
 * response.//w  w w  . j  a  v  a  2  s.c  o m
 * <p>
 * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
 * that no filters are applied to a forwarded or included resource,
 * because they were already done for the original request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
private void invoke(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader contextClassLoader = context.getLoader().getClassLoader();

    if (oldCCL != contextClassLoader) {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } else {
        oldCCL = null;
    }

    // Initialize local variables we may need
    HttpServletRequest hrequest = null;
    if (request instanceof HttpServletRequest)
        hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = null;
    if (response instanceof HttpServletResponse)
        hresponse = (HttpServletResponse) response;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;

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

    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            //                if (debug >= 2)
            //                    log("  Allocating servlet instance");
            servlet = wrapper.allocate();
            //                if ((debug >= 2) && (servlet == null))
            //                    log("    No servlet instance returned!");
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = e;
        servlet = null;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }

    // Get the FilterChain Here
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        String jspFile = wrapper.getJspFile();
        if (jspFile != null)
            request.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
        else
            request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.BEFORE_DISPATCH_EVENT, servlet, request, response);
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
        // Servlet Service Method is called by the FilterChain
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
    } catch (ClientAbortException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        ioException = e;
    } catch (IOException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        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);

        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        servletException = e;
    } catch (RuntimeException e) {
        request.removeAttribute(Globals.JSP_FILE_ATTR);
        support.fireInstanceEvent(InstanceEvent.AFTER_DISPATCH_EVENT, servlet, request, response);
        log(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }

    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        log.error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
        //FIXME Exception handling needs to be simpiler to what is in the StandardWrapperValue
    }

    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (ServletException e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        log(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(
                sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }

    // Reset the old context class loader
    if (oldCCL != null)
        Thread.currentThread().setContextClassLoader(oldCCL);

    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null)
        throw ioException;
    if (servletException != null)
        throw servletException;
    if (runtimeException != null)
        throw runtimeException;

}