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:com.meltmedia.cadmium.servlets.MaintenanceFilter.java

@Override
public void doFilter(HttpServletRequest httpReq, HttpServletResponse httpRes, FilterChain chain)
        throws IOException, ServletException {
    try {/*w  ww .  j  av a 2 s .c o  m*/
        String contextPath = httpReq.getContextPath();
        String uri = httpReq.getRequestURI();
        if (contextPath != null && contextPath.trim().length() > 0 && uri.startsWith(contextPath)) {
            uri = uri.substring(contextPath.length());
        }
        if (!on || (ignorePath != null && uri.startsWith(ignorePath))) {
            logger.trace("Serving request server:{}, uri:{}", httpReq.getServerName(), uri);
            chain.doFilter(httpReq, httpRes);
            return;
        }

        httpRes.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        httpRes.setContentType(MediaType.TEXT_HTML);
        InputStream in = null;
        InputStreamReader reader = null;
        try {
            in = MaintenanceFilter.class.getResourceAsStream("/maintenance.html");
            if (in == null) {
                in = MaintenanceFilter.class.getResourceAsStream("./maintenance.html");
            }
            reader = new InputStreamReader(in, "UTF-8");
            IOUtils.copy(reader, httpRes.getWriter());
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(httpRes.getWriter());
        }
    } catch (IOException ioe) {
        logger.trace("Failed in maint filter.", ioe);
        throw ioe;
    } catch (ServletException se) {
        logger.trace("Failed in maint filter.", se);
        throw se;
    } catch (Throwable t) {
        logger.trace("Failed in maint filter.", t);
        throw new ServletException(t);
    }
}

From source file:org.dspace.rdf.providing.DataProviderServlet.java

/**
 * Processes requests for both HTTP//from   ww  w.j  ava2  s.c o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // set all incoming encoding to UTF-8
    request.setCharacterEncoding("UTF-8");

    // we expect either a path containing only the language information
    // or a path in the form /handle/<prefix>/<suffix>[/language].
    String lang = this.detectLanguage(request);
    String cType = this.detectContentType(request, lang);
    String pathInfo = request.getPathInfo();

    log.debug("lang = " + lang + ", cType = " + cType + " and pathInfo: " + pathInfo);
    if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) {
        String dspaceURI = DSpaceServicesFactory.getInstance().getConfigurationService()
                .getProperty("dspace.url");
        this.serveNamedGraph(dspaceURI, lang, cType, response);
        return;
    }

    // remove trailing slash of the path info and split it.
    String[] path = request.getPathInfo().substring(1).split("/");
    // if we have 2 slashes or less, we sent repository information (see above)
    assert path.length >= 2;

    String handle = path[0] + "/" + path[1];

    log.debug("Handle: " + handle + ".");

    // As we offer a public sparql endpoint, all information that we stored
    // in the triplestore is public. It is important to check whether a
    // DSpaceObject is readable for a anonym user before storing it in the
    // triplestore. It is important to remove DSpaceObjects from the
    // triplestore, that gets revoked or become restricted. As this is done
    // by RDFizer and RDFUtil we do not have to take care for permissions here!
    Context context = null;
    DSpaceObject dso = null;
    try {
        context = new Context(Context.Mode.READ_ONLY);
        dso = handleService.resolveToObject(context, handle);
    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage(), ex);
        context.abort();
        // probably a problem with the db connection => send Service Unavailable
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    } catch (IllegalStateException ex) {
        log.error("Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex);
        context.abort();
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    if (dso == null) {
        log.info("Cannot resolve handle '" + handle + "' to dso. => 404");
        context.abort();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    String identifier = null;
    try {
        identifier = RDFUtil.generateIdentifier(context, dso);
    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage(), ex);
        context.abort();
        // probably a problem with the db connection => send Service Unavailable
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }
    if (identifier == null) {
        // cannot generate identifier for dso?!
        log.error("Cannot generate identifier for UUID " + dso.getID().toString() + "!");
        context.abort();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    log.debug("Loading and sending named graph " + identifier + ".");
    context.abort();
    this.serveNamedGraph(identifier, lang, cType, response);

}

From source file:cc.kune.core.server.searcheable.SearchEngineServletFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException, DefaultException {
    if (filterConfig == null) {
        return;//from  w  w  w  . j  a  va  2s  .  c o  m
    }

    if (request instanceof HttpServletRequest) {

        final HttpServletRequest httpReq = (HttpServletRequest) request;
        final StringBuffer url = httpReq.getRequestURL();

        final String queryString = httpReq.getQueryString();

        if ((queryString != null) && (queryString.contains(SiteParameters.ESCAPED_FRAGMENT_PARAMETER))) {
            if (!enabled) {
                final HttpServletResponse httpRes = (HttpServletResponse) response;
                httpRes.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Search Engine service disabled temporally");
                return;
            }
            // rewrite the URL back to the original #! version
            // remember to unescape any %XX characters
            final String urlWithEscapedFragment = request
                    .getParameter(SiteParameters.ESCAPED_FRAGMENT_PARAMETER);
            final String newUrl = url.append("?").append(queryString).toString()
                    .replaceFirst(SiteParameters.ESCAPED_FRAGMENT_PARAMETER, SiteParameters.NO_UA_CHECK)
                    .replaceFirst("/ws", "") + "#" + urlWithEscapedFragment;

            LOG.info("New url with hash: " + newUrl);

            final String page = "In development";
            // return the snapshot
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=UTF-8");
            response.getOutputStream().write(page.getBytes());
        } else {
            try {
                // not an _escaped_fragment_ URL, so move up the chain of
                // servlet (filters)
                chain.doFilter(request, response);
            } catch (final ServletException e) {
                LOG.error("Servlet exception caught: " + e);
            }
        }
    }
}

From source file:com.mengka.diamond.server.controller.ConfigController.java

/**
 * /*from   w  w w. j av  a2s .co  m*/
 * ?dataIdgroupId
 * @param request
 * @param response
 * @param probeModify
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.PROBE_MODIFY_REQUEST) String probeModify) {
    response.setHeader("Content-Type", "text/html;charset=utf-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (!StringUtils.equals(md5, key.getMd5())) {
            resultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                    .append(Constants.LINE_SEPARATOR);
        }
    }

    String returnHeader = resultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(resultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
        // ignore
    }

    request.setAttribute("content", returnHeader);
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "200";
}

From source file:com.flexive.war.servlet.TestRunnerServlet.java

/**
 * {@inheritDoc}/*from w  w w. j a  va 2s  .c  o m*/
 */
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    String cmd = URLDecoder.decode(request.getRequestURI(), "UTF8");
    if (cmd != null && cmd.lastIndexOf('/') > 0)
        cmd = cmd.substring(cmd.lastIndexOf('/') + 1);
    if (CMD_AVAILABLE.equals(cmd)) {
        boolean available = false;
        try {
            Class.forName("com.flexive.testRunner.FxTestRunner");
            available = true;
        } catch (Exception e) {
            LOG.error(e);
        }
        response.setStatus(available ? HttpServletResponse.SC_OK : HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.getWriter().write(String.valueOf(available));
    } else if (CMD_RUN.equals(cmd)) {
        String outputPath = request.getParameter(PARAM_OUTPUTPATH);
        try {
            Class runner = Class.forName("com.flexive.testRunner.FxTestRunner");
            Method check = runner.getMethod("checkTestConditions", String.class, Boolean.class);
            Boolean status = false;
            if (!StringUtils.isEmpty(outputPath))
                status = (Boolean) check.invoke(null, String.valueOf(outputPath), Boolean.FALSE);
            if (!status) {
                response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
                response.getWriter()
                        .write("Invalid output path, assertations not enabled or test division not definied!");
                return;
            }
            Method exec = runner.getMethod("runTests", String.class);
            exec.invoke(null, outputPath);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("Tests started.");
        } catch (Exception e) {
            LOG.error(e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error: " + e.getMessage());
        }
    } else if (CMD_RUNNING.equals(cmd)) {
        try {
            Class runner = Class.forName("com.flexive.testRunner.FxTestRunner");
            Method check = runner.getMethod("isTestInProgress");
            Boolean status = (Boolean) check.invoke(null);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(String.valueOf(status));
        } catch (Exception e) {
            LOG.error(e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error: " + e.getMessage());
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        response.getWriter().write("Unknown command: " + cmd);
    }
}

From source file:sse.es.EventSourceServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (acceptsEventStream(request)) {
        Map<String, String> params = parsePostBody(request.getInputStream());
        String clientId = params.get("clientId");
        EventSource eventSource = newEventSource(request, clientId);
        if (eventSource == null) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } else {/*from ww w  .ja  v  a  2 s  .  c o m*/
            respond(request, response);
            Continuation continuation = ContinuationSupport.getContinuation(request);
            // Infinite timeout because the continuation is never resumed,
            // but only completed on close
            continuation.setTimeout(0L);
            continuation.suspend(response);
            EventSourceEmitter emitter = new EventSourceEmitter(eventSource, continuation);
            emitter.scheduleHeartBeat();
            String lastEventId = params.get("Last-Event-ID");
            if (lastEventId != null && !"".equals(lastEventId.trim())) {
                resume(eventSource, emitter, lastEventId);
            } else {
                open(eventSource, emitter);
            }
        }
        return;
    }
    super.doPost(request, response);
}

From source file:de.logicline.splash.controller.UserController.java

/**
 * user login without captcha verification
 * needs configured heroku connector add on
 * returns specific error if auth failed or config not done
 * //from  w  w w .  j av a  2  s . c  o  m
 * @param userEntity credentials from the web client
 * @param response
 * 
 * @return
 */
@RequestMapping(value = "/user/login", method = RequestMethod.POST)
public @ResponseBody Map<String, String> userLogin(@RequestBody final UserEntity userEntity,
        HttpServletResponse response) {
    UserEntity userEntityTmp = userService.getUserByName(userEntity.getUsername());

    if (userEntityTmp == null || !BCrypt.checkpw(userEntity.getPassword(), userEntityTmp.getPassword())) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }

    Map<String, String> responseMap = new HashMap<String, String>();
    String token = userEntityTmp.getToken();
    responseMap.put("token", token);
    responseMap.put("userId", String.valueOf(userEntityTmp.getUserId()));
    responseMap.put("role", userEntityTmp.getRole());

    try {
        ContactEntity contactEntity = userService.getContact(token);
        if (contactEntity != null) {
            responseMap.put("firstName", contactEntity.getFirstName());
            responseMap.put("lastName", contactEntity.getLastName());
        }
    } catch (Exception e) {
        LOGGER.error("Exception during getContact()", e);
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return null;
    }

    return responseMap;
}

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

/**
 * Returns the sitemap./*from w w w.  j  ava 2  s  .co  m*/
 * 
 * @param context the specified context
 */
@RequestProcessing(value = { "/sitemap.xml" }, method = HTTPRequestMethod.GET)
public void sitemap(final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);

    final Sitemap sitemap = new Sitemap();

    try {
        final JSONObject preference = preferenceQueryService.getPreference();

        addArticles(sitemap, preference);
        addNavigations(sitemap, preference);
        addTags(sitemap, preference);
        addArchives(sitemap, preference);

        LOGGER.log(Level.INFO, "Generating sitemap....");
        final String content = sitemap.toString();
        LOGGER.log(Level.INFO, "Generated sitemap");
        renderer.setContent(content);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Get blog article feed error", e);

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

From source file:ee.ria.xroad.common.util.healthcheck.MaintenanceModeTest.java

/**
 * Tests {@link HealthCheckPort} operation when it's in maintenance mode
 * - verifies that internal provider does not get called during maintenance mode
 * - verifies that HTTP status code 503 with the maintenance message is returned due to maintenance mode
 * @throws IOException client operation can throw an IOException that should fail the test
 *//* w  ww .  jav a  2  s  . com*/
@Test
public void maintenanceModeOnShouldPreventProviderCalls() throws IOException {
    testPort.setMaintenanceMode(true);
    try (CloseableHttpResponse response = testClient.execute(healthCheckGet)) {
        verify(testProvider, times(0)).get();
        assertEquals(HttpServletResponse.SC_SERVICE_UNAVAILABLE, response.getStatusLine().getStatusCode());
        HttpEntity responseEntity = response.getEntity();
        assertNotNull("HealthCheckPorts's response did not contain a message", responseEntity);
        String responseMessage = IOUtils.toString(responseEntity.getContent());
        assertThat("HealthCheckPorts's response did not contain maintenance message", responseMessage,
                containsString(HealthCheckPort.MAINTENANCE_MESSAGE));
    }
}

From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TextHtmlContentExceptionWrapper {
    try {//w w  w  .  j  a  v  a  2s .c  o  m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<Attachment> attachments = new ArrayList<Attachment>();
        Map<String, String> formValues = new HashMap<String, String>();

        try {
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {

                if (item.isFormField()) {
                    formValues.put(item.getFieldName(), item.getString());
                } else {
                    Attachment attachment = new Attachment();
                    attachment.setAttachmentData(readInputStream(item.getInputStream()));
                    attachment.setFilename(item.getName());
                    attachment.setMimeType(item.getContentType());
                    attachments.add(attachment);
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code
            return;
        }

        for (int i = 0; i < attachments.size(); i++) {
            String description = formValues
                    .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i);
            if (description == null) {
                throw new IllegalArgumentException(
                        "Missing description " + i + 1 + " of " + attachments.size());
            }
            attachments.get(0).setDescription(description);
        }

        TaskHandle taskHandle = getTaskHandle(formValues);

        UploadResult result = doUpload(response, attachments, taskHandle);

        response.setContentType("text/html");
        response.getWriter()
                .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result)));
    } catch (Exception e) {
        throw new TextHtmlContentExceptionWrapper(e.getMessage(), e);
    }
}