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.b3log.solo.processor.RepairProcessor.java

/**
 * Removes all data./*  w  ww  .ja va 2 s .  co  m*/
 * 
 * @param context the specified context
 */
@RequestProcessing(value = { "/rm-all-data.do" }, method = HTTPRequestMethod.POST)
public void removeAllDataPOST(final HTTPRequestContext context) {
    LOGGER.info("Removing all data....");

    PageCaches.removeAll();

    boolean succeed = false;
    try {
        remove(ArchiveDateArticleRepositoryImpl.getInstance());
        remove(ArchiveDateRepositoryImpl.getInstance());
        remove(ArticleRepositoryImpl.getInstance());
        remove(CommentRepositoryImpl.getInstance());
        remove(LinkRepositoryImpl.getInstance());
        remove(PageRepositoryImpl.getInstance());
        remove(PreferenceRepositoryImpl.getInstance());
        remove(StatisticRepositoryImpl.getInstance());
        remove(TagArticleRepositoryImpl.getInstance());
        remove(TagRepositoryImpl.getInstance());
        remove(UserRepositoryImpl.getInstance());

        succeed = true;
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        LOGGER.log(Level.WARNING, "Removed partial data only");
    }

    final StringBuilder htmlBuilder = new StringBuilder();
    htmlBuilder.append("<html><head><title>Result</title></head><body>");

    try {
        final TextHTMLRenderer renderer = new TextHTMLRenderer();
        context.setRenderer(renderer);
        if (succeed) {
            htmlBuilder.append("Removed all data!");
        } else {
            htmlBuilder.append("Refresh this page and run this remover again.");
        }
        htmlBuilder.append("</body></html>");

        renderer.setContent(htmlBuilder.toString());
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        try {
            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    LOGGER.info("Removed all data....");
}

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

/**
 * Modifies a <tt>Conference</tt> with ID <tt>target</tt> in (the
 * associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> to modify in (the
 * associated) <tt>Videobridge</tt>
 * @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   ww w  . j av a2  s.co m
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPatchConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Conference conference = videobridge.getConference(target, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } 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)
                        && !requestConferenceIQ.getID().equals(conference.getID()))) {
                    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:com.ibm.jaggr.service.impl.AggregatorImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    if (log.isLoggable(Level.FINEST))
        log.finest("doGet: URL=" + req.getRequestURI()); //$NON-NLS-1$

    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {//from  ww  w .  java  2s. co  m
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                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.REQUESTEDMODULES_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();
                if (expires > 0) {
                    resp.addHeader("Cache-Control", "max-age=" + expires); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            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(), AggregatorCommandProvider.EYECATCHER + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.CMD_VALIDATEDEPS + " " + //$NON-NLS-1$
                            getName() + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.PARAM_CLEAN,
                            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();
    }
}

From source file:com.att.ajsc.csilogging.common.CSILoggingUtils.java

public void finalizeRequest(HttpServletRequest request, HttpServletResponse response) {

    logger.debug("In...:finalizeRequest");
    String servicename = UtilLib.getServiceName(request);

    PerformanceTrackingBean perfTrackerBean = (PerformanceTrackingBean) request
            .getAttribute(PERFORMANCE_TRACKER_BEAN);
    long startTime = (long) request.getAttribute(CommonNames.START_TIME);
    AuditRecord ar = new AuditRecord();
    try {//from   w  w  w  .j av a 2s. com
        logger.debug("Starting application specific handling...:finalizeRequest");
        // request.setAttribute(CommonNames.AUDIT_RECORD, ar);
        // request.setAttribute(CommonNames.ATTR_START_TIME,
        // Long.valueOf(startTime).toString());
        perfTrackerBean.setAuditRecord(ar);
        servicename = LoggerNameConverter.convertNormalizedName(request, servicename);

        perfTrackerBean.setServiceName(servicename);

        perfTrackerBean.setRequestContentLen(request.getContentLength());
        perfTrackerBean.setResponseMsgSize(getResponseLength(request));
        perfTrackerBean.setMethod(request.getMethod());

        ar.setInstanceName(SystemParams.instance().getInstanceName());
        ar.setInitiatedTimestamp(UtilLib.epochToXmlGC(startTime));
        ar.setVtier(SystemParams.instance().getVtier());
        ar.setCluster(SystemParams.instance().getCluster());
        ar.setHostName(SystemParams.instance().getHostName());
        ar.setHostIPAddress(SystemParams.instance().getIpAddress());
        ar.setSubject("CW.pub.spm2." + servicename + ".response");
        ar.setMode("");
        ar.setServiceKeyData1("");
        ar.setServiceKeyData2("");
        ar.setSourceClass(CommonNames.SOURCE_CLASS);
        ar.setSourceMethod(CommonNames.AUDIT_LOGGER_NAME);
        ar.setTransactionName(servicename);
        /*
         * ar.setApplicationId(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setConversationId(request.getAttribute(CommonNames.
         * CSI_CONVERSATION_ID));
         * ar.setUniqueTransactionId(request.getAttribute(CommonNames.
         * CSI_UNIQUE_TXN_ID));
         * ar.setOriginalMessageId(request.getAttribute(CommonNames.
         * CSI_MESSAGE_ID));
         * ar.setOriginatorId(request.getAttribute(CommonNames.
         * CSI_ORIGINATOR_ID));
         * ar.setClientApp(UtilLib.ifNullThenEmpty(request.getAttribute(
         * CommonNames.CSI_CLIENT_APP))); ar.setOriginationSystemId("N/A");
         * ar.setOriginationSystemName(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setOriginationSystemVersion(request.getAttribute(CommonNames.
         * CSI_VERSION));
         */

        ar.setApplicationId(perfTrackerBean.getUserName());
        ar.setConversationId(perfTrackerBean.getConversationId());
        ar.setUniqueTransactionId(perfTrackerBean.getUniqueTransactionId());
        ar.setOriginalMessageId(perfTrackerBean.getOriginalMessageId());
        ar.setOriginatorId(perfTrackerBean.getOriginatorId());
        ar.setClientApp(UtilLib.ifNullThenEmpty(perfTrackerBean.getClientApp()));
        ar.setOriginationSystemId("N/A");
        ar.setOriginationSystemName(perfTrackerBean.getUserName());
        ar.setOriginationSystemVersion(perfTrackerBean.getOriginationSystemVersion());

        // new fields added per new schema
        ar.setClientIP(request.getRemoteAddr());
        ar.setHttpMethod(perfTrackerBean.getMethod());
        ar.setRequestURL(request.getPathInfo());

        // PerformanceTracking.initPerfTrack(request,servicename);
        PerformanceTracking.initPerfTrack(perfTrackerBean, servicename);
        // PerformanceTracking.addPerfTrack(request, "Main", "I",
        // startTime.toString(), servicename);

        int httpCode = response.getStatus();

        if (httpCode == HttpServletResponse.SC_UNAUTHORIZED) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_401_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_FORBIDDEN) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_403_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_NOT_IMPLEMENTED) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_501_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_503_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (400 <= httpCode && httpCode <= 499) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_4NN_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == 500) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_500_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

        else {
            ar.setResponseDescription(CommonNames.CSI_SUCCESS);
            ar.setResponseCode(CommonNames.CSI_SUCCESS_RESPONSE_CODE);
            ar.setTransactionStatus("C");
        }

        // Enhance CSI logging to use the CAET error code

        if (response.getHeader(CommonNames.CAET_RestErrorCode) != null
                || response.getHeader(CommonNames.CAET_CingularErrorCode) != null) {

            // if(request.getHeader("X-CAET-CingularErrorCode") != null){
            if ("Y".equals(request.getAttribute(CommonNames.AJSC_CAET_IS_REST_SERVICE))) {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCategory));
                ar.setResponseDescription(response.getHeader(CommonNames.CAET_RestErrorDescription));

            } else

            {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCode));

                ar.setResponseDescription(response.getHeader(CommonNames.CAET_CingularErrorDescription));

            }

            ar.setFaultCode(response.getHeader(CommonNames.CAET_FaultCode));

            ar.setFaultDescription(response.getHeader(CommonNames.CAET_FaultDesc));

            ar.setFaultLevel(CommonNames.ERROR);

            ar.setFaultEntity(response.getHeader(CommonNames.CAET_FaultEntity));

            ar.setTransactionStatus("E");

            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));

            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));

            ar.setExternalFaultCode(String.valueOf(httpCode));

            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

    }

    catch (Exception e) {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        ar.setResponseCode(CommonNames.CSI_GENERIC_UNKNOWN_ERROR);
        ar.setResponseDescription(CommonErrors.DEF_5NN_FAULT_DESC);
        ar.setFaultEntity("CSI");
        ar.setFaultCode(CommonErrors.DEF_5NN_FAULT_CODE);
        ar.setFaultDescription(e.getMessage());
        ar.setFaultLevel("ERROR");
        ar.setFaultSequenceNumber("1");
        ar.setTransactionStatus("E");
        ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
        // ar.setFaultTimestamp(UtilLib.epochToXmlGC(((Long)System.nanoTime()/1000000).longValue()));
        logger.error("EXCEPTION - " + e.getMessage());
    }

    finally {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        if (ar != null) {

            if (perfTrackerBean != null && !perfTrackerBean.isAsync()) {
                perfTrackerBean.setAuditRecord(ar);
                logger.debug("Before calling completeLogging");
                completeLogging(request, servicename);
            }

        } else {
            logger.debug("Audit Record is null,abort logging");
        }
    }

}

From source file:org.mortbay.jetty.webapp.WebAppContext.java

/** 
 * @see org.mortbay.jetty.handler.ContextHandler#handle(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
 *//*from w w  w .ja  va  2 s.c om*/
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    if (_unavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else
        super.handle(target, request, response, dispatch);
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

private void sendServiceUnavailableResponse(HttpServletResponse resp, String reason)
        throws IOException, JsonGenerationException, JsonMappingException {
    resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    resp.setContentType("application/json");
    OutputStream os = resp.getOutputStream();

    Map<String, Object> responseMap = new HashMap<String, Object>();
    responseMap.put("error", "service_unavailable");
    responseMap.put("reason", reason);
    mapper.writeValue(os, responseMap);// ww  w. j a  va 2 s  . c om
}

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

@POST
@Path("recordings/{id}")
@RestQuery(name = "setRecordingState", description = "Set the status of a given recording, registering it if it is new", pathParameters = {
        @RestParameter(description = "The ID of a given recording", isRequired = true, name = "id", type = Type.STRING) }, restParameters = {
                @RestParameter(description = "The state of the recording. Must be one of the following: unknown, capturing, capture_finished, capture_error, manifest, manifest_error, manifest_finished, compressing, compressing_error, uploading, upload_finished, upload_error.", isRequired = true, name = "state", type = Type.STRING) }, reponses = {
                        @RestResponse(description = "{id} set to {state}", responseCode = HttpServletResponse.SC_OK),
                        @RestResponse(description = "{id} or state {state} is empty or the {state} is not known", responseCode = HttpServletResponse.SC_BAD_REQUEST),
                        @RestResponse(description = "If no capture agent state service is available", responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response setRecordingState(@PathParam("id") String id, @FormParam("state") String state) {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();

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

    if (service.setRecordingState(id, state)) {
        return Response.ok(id + " set to " + state).build();
    } else {//from   w w  w  . j a  va2 s .  co  m
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:org.b3log.solo.processor.FeedProcessor.java

/**
 * Blog articles RSS output.//from   www .  j av a  2 s.  c o  m
 * 
 * @param context the specified context
 */
@RequestProcessing(value = { "/blog-articles-rss.do" }, method = { HTTPRequestMethod.GET,
        HTTPRequestMethod.HEAD })
public void blogArticlesRSS(final HTTPRequestContext context) {
    final HttpServletResponse response = context.getResponse();
    final RssRenderer renderer = new RssRenderer();
    context.setRenderer(renderer);

    final Channel channel = new Channel();
    try {
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final String blogTitle = preference.getString(Preference.BLOG_TITLE);
        final String blogSubtitle = preference.getString(Preference.BLOG_SUBTITLE);
        final String blogHost = preference.getString(Preference.BLOG_HOST);

        channel.setTitle(StringEscapeUtils.escapeXml(blogTitle));
        channel.setLastBuildDate(TimeZones.getTime(preference.getString(Preference.TIME_ZONE_ID)));
        channel.setLink("http://" + blogHost);
        channel.setAtomLink("http://" + blogHost + "/blog-articles-rss.do");
        channel.setGenerator("B3log Solo, ver " + SoloServletListener.VERSION);
        final String localeString = preference.getString(Preference.LOCALE_STRING);
        final String country = Locales.getCountry(localeString).toLowerCase();
        final String language = Locales.getLanguage(localeString).toLowerCase();
        channel.setLanguage(language + '-' + country);
        channel.setDescription(blogSubtitle);

        final List<Filter> filters = new ArrayList<Filter>();
        filters.add(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true));
        filters.add(new PropertyFilter(Article.ARTICLE_VIEW_PWD, FilterOperator.EQUAL, ""));
        final Query query = new Query().setCurrentPageNum(1).setPageSize(ENTRY_OUTPUT_CNT)
                .setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters))
                .addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING).setPageCount(1);

        final JSONObject articleResult = articleRepository.get(query);
        final JSONArray articles = articleResult.getJSONArray(Keys.RESULTS);

        final boolean hasMultipleUsers = Users.getInstance().hasMultipleUsers();
        String authorName = "";

        if (!hasMultipleUsers && 0 != articles.length()) {
            authorName = articleUtils.getAuthor(articles.getJSONObject(0)).getString(User.USER_NAME);
        }

        final boolean isFullContent = "fullContent".equals(preference.getString(Preference.FEED_OUTPUT_MODE));

        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            final Item item = new Item();
            channel.addItem(item);
            final String title = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));
            item.setTitle(title);
            final String description = isFullContent
                    ? StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT))
                    : StringEscapeUtils.escapeXml(article.optString(Article.ARTICLE_ABSTRACT));
            item.setDescription(description);
            final Date pubDate = (Date) article.get(Article.ARTICLE_UPDATE_DATE);
            item.setPubDate(pubDate);
            final String link = "http://" + blogHost + article.getString(Article.ARTICLE_PERMALINK);
            item.setLink(link);
            item.setGUID(link);

            final String authorEmail = article.getString(Article.ARTICLE_AUTHOR_EMAIL);
            if (hasMultipleUsers) {
                authorName = StringEscapeUtils
                        .escapeXml(articleUtils.getAuthor(article).getString(User.USER_NAME));
            }

            item.setAuthor(authorEmail + "(" + authorName + ")");

            final String tagsString = article.getString(Article.ARTICLE_TAGS_REF);
            final String[] tagStrings = tagsString.split(",");
            for (int j = 0; j < tagStrings.length; j++) {
                final org.b3log.solo.model.feed.rss.Category catetory = new org.b3log.solo.model.feed.rss.Category();
                item.addCatetory(catetory);
                final String tag = tagStrings[j];
                catetory.setTerm(tag);
            }
        }

        renderer.setContent(channel.toString());
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Get blog article rss error", e);

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

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or
 * JSON according to the XACML 3.0 Specifications for both.
 *
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from   w  w w  . java2s. c om*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // no point in doing any work if we know from the get-go that we cannot do anything with the request
    //
    if (status.getLoadedRootPolicies().size() == 0) {
        logger.warn("Request from PEP at " + request.getRequestURI()
                + " for service when PDP has No Root Policies loaded");
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    XACMLRest.dumpRequest(request);
    //
    // Set our no-cache header
    //
    response.setHeader("Cache-Control", "no-cache");
    //
    // They must send a Content-Type
    //
    if (request.getContentType() == null) {
        logger.warn("Must specify a Content-Type");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
        return;
    }
    //
    // Limit the Content-Length to something reasonable
    //
    if (request.getContentLength() > Integer
            .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
        String message = "Content-Length larger than server will accept.";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    if (request.getContentLength() <= 0) {
        String message = "Content-Length is negative";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    ContentType contentType = null;
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (Exception e) {
        String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // What exactly did they send us?
    //
    String incomingRequestString = null;
    Request pdpRequest = null;
    if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
        //
        // Read in the string
        //
        StringBuilder buffer = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            incomingRequestString = buffer.toString();
        }
        logger.info(incomingRequestString);
        //
        // Parse into a request
        //
        try {
            if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                pdpRequest = JSONRequest.load(incomingRequestString);
            } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                    || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
                pdpRequest = DOMRequest.load(incomingRequestString);
            }
        } catch (Exception e) {
            logger.error("Could not parse request", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }
    } else {
        String message = "unsupported content type" + request.getContentType();
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Did we successfully get and parse a request?
    //
    if (pdpRequest == null || pdpRequest.getRequestAttributes() == null
            || pdpRequest.getRequestAttributes().size() <= 0) {
        String message = "Zero Attributes found in the request";
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Run it
    //
    try {
        //
        // Get the pointer to the PDP Engine
        //
        PDPEngine myEngine = null;
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
        }
        if (myEngine == null) {
            String message = "No engine loaded.";
            logger.error(message);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
            return;
        }
        //
        // Send the request and save the response
        //
        long lTimeStart, lTimeEnd;
        Response pdpResponse = null;

        // TODO - Make this unnecessary
        // TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in
        // the middle of processing
        // TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide()
        // method).
        // TODO Using synchronize will slow down processing of PEP requests, possibly by a significant
        // amount.
        // TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate
        // this sychronized block.
        // TODO
        // TODO This problem was found by starting one PDP then
        // TODO RestLoadTest switching between 2 configurations, 1 second apart
        // TODO both configurations contain the datarouter policy
        // TODO both configurations already have all policies cached in the PDPs config directory
        // TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval
        // TODO With that configuration this code (without the synchronized) throws a NullPointerException
        // TODO within a few seconds.
        //
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
            try {
                lTimeStart = System.currentTimeMillis();
                pdpResponse = myEngine.decide(pdpRequest);
                lTimeEnd = System.currentTimeMillis();
            } catch (PDPException e) {
                String message = "Exception during decide: " + e.getMessage();
                logger.error(message);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                return;
            }
        }
        requestLogger.info(lTimeStart + "=" + incomingRequestString);
        if (logger.isDebugEnabled()) {
            logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
        }
        //
        // Convert Response to appropriate Content-Type
        //
        if (pdpResponse == null) {
            requestLogger.info(lTimeStart + "=" + "{}");
            throw new Exception("Failed to get response from PDP engine.");
        }
        //
        // Set our content-type
        //
        response.setContentType(contentType.getMimeType());
        //
        // Convert the PDP response object to a String to
        // return to our caller as well as dump to our loggers.
        //
        String outgoingResponseString = "";
        if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = JSONResponse.toString(pdpResponse, false);
            }
        } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = DOMResponse.toString(pdpResponse, false);
            }
        }
        //
        // lTimeStart is used as an ID within the requestLogger to match up
        // request's with responses.
        //
        requestLogger.info(lTimeStart + "=" + outgoingResponseString);
        response.getWriter().print(outgoingResponseString);
    } catch (Exception e) {
        String message = "Exception executing request: " + e;
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return;
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

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

public void doPost(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response)
        throws javax.servlet.ServletException, java.io.IOException {

    if (!isServePages()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Website is currently updating configuration. Please try again later.");
        return;//from  www.j a  v  a  2s  .  co  m
    }

    String path = request.getServletPath() + (request.getPathInfo() != null ? request.getPathInfo() : "");

    try {

        if (path.equals("/login")) {

            doLogin(request, response);
            return;

        } else if (path.equals("/logout")) {

            String domain = request.getParameter("domain");
            _core.logout(domain, request.getSession(), request, response, true);
            sendRedirect(request, response, request.getParameter("redirect"));

        } else if (path.equals("/ajaxform")) {
            this.dispatchAjaxForm(request, response);
        } else {
            this.doGet(request, response);
        }

    } catch (AjaxFailureException exc) {
        handleAjaxFailure(exc, request, response);
    } catch (Exception exc) {
        _log.error("Exception in processing of request URL " + String.valueOf(request.getRequestURL()), exc);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, exc);
        throw new ServletException(exc);
    } catch (Error err) {
        _log.error("Error in processing of request URL " + String.valueOf(request.getRequestURL()), err);
        request.setAttribute(WGACore.ATTRIB_EXCEPTION, err);
        throw new ServletException(err);
    }
}