Example usage for javax.servlet.http HttpServletResponse SC_OK

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

Introduction

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

Prototype

int SC_OK

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

Click Source Link

Document

Status code (200) indicating the request succeeded normally.

Usage

From source file:fr.gael.dhus.server.http.webapp.search.controller.SearchController.java

@PreAuthorize("hasRole('ROLE_SEARCH')")
@RequestMapping(value = "/suggest/{query}")
public void suggestions(@PathVariable String query, HttpServletResponse res) throws IOException {
    List<String> suggestions = searchService.getSuggestions(query);
    res.setStatus(HttpServletResponse.SC_OK);
    res.setContentType("text/plain");
    try (ServletOutputStream outputStream = res.getOutputStream()) {
        for (String suggestion : suggestions) {
            outputStream.println(suggestion);
        }/*  w  w  w.ja v  a  2 s . c  o  m*/
    }
}

From source file:ch.admin.suis.msghandler.servlet.MonitorServlet.java

private void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  ww . j  av  a  2  s  .  c o  m*/
        FilterClient filterClient = handleParam(request);
        List<DBLogEntry> dbLogEntries = filterClient.filter(mhContext.getLogService().getAllEntries());
        response.getWriter().println(toJson(dbLogEntries, dbLogEntries.getClass()));
        response.setContentType(JSON);
        response.setStatus(HttpServletResponse.SC_OK);

    } catch (LogServiceException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new ServletException(ex);

    } catch (MonitorException ex) {
        LOG.error("Unable to process the task: " + ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType(TEXT);
        response.getWriter().println("Invalid request: " + ex.getMessage());

    } catch (IOException ex) {
        LOG.fatal("MonitorServlet: " + ex.getMessage(), ex);
        throw ex;
    }
}

From source file:com.almende.eve.transport.http.EveServlet.java

/**
 * Handle hand shake.//from  ww w . j av  a2 s.c  o  m
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 * @return true, if successful
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private boolean handleHandShake(final HttpServletRequest req, final HttpServletResponse res)
        throws IOException {
    final String time = req.getHeader("X-Eve-requestToken");

    if (time == null) {
        return false;
    }
    final String url = req.getRequestURI();
    final String id = getId(url);
    final HttpTransport transport = HttpService.get(myUrl, id);
    if (transport != null) {
        final String token = transport.getTokenstore().get(time);
        if (token == null) {
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        } else {
            res.setHeader("X-Eve-replyToken", token);
            res.setStatus(HttpServletResponse.SC_OK);
            res.flushBuffer();
        }
    }
    return true;
}

From source file:com.ns.cm.ProvisionServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // InputStream is = request.getInputStream ();
    // byte[] bytes = readAll (is);

    PrintWriter out = response.getWriter();
    out.println("<HTML><BODY>");
    String uid = request.getParameter("uid");
    String password = request.getParameter("password");
    if (uid.equalsIgnoreCase("secretUID") && password.equalsIgnoreCase("secretPW")) {
        out.println("<BR>Welcome back " + uid.toUpperCase());
    } else {//w  ww. j av  a 2s .c  om
        out.println("<BR> Incorrect userid/password!");
        String jsForBack = "<script> function goBack() { window.history.back() } </script>";
        out.println(jsForBack);
        out.println("<button onclick=\"goBack()\">Go Back</button>");
    }
    out.println("</BODY></HTML>");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

}

From source file:biz.taoconsulting.dominodav.methods.PUT.java

/**
 * (non-Javadoc)//from  w  w w.j  a  v a  2  s  . c om
 * 
 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
 */
public void action() throws Exception {
    IDAVRepository rep = this.getRepository();

    // uri is the unique identifier on the host includes servlet and
    // repository but not server
    String curURI = (String) this.getHeaderValues().get("uri");
    IDAVResource resource = null;
    InputStream instream = null;
    OutputStream out = null;
    boolean success = true;
    String relockToken = this.getRelockToken(this.getReq());
    LockManager lm = this.getLockManager();
    Long TimeOutValue = this.getTimeOutValue(this.getReq());
    // String lockrequestorName =
    // this.getOwnerFromXMLLockRequest(this.getReq());
    int status = HttpServletResponse.SC_OK; // We presume success
    LockInfo li = null;
    try {
        curURI = java.net.URLDecoder.decode(curURI, "UTF-8");
    } catch (Exception e) {
    }

    try {
        // LOGGER.info("getResource");
        resource = rep.getResource(curURI, true);

    } catch (DAVNotFoundException e) {
        // This exception isn't a problem since we just can create the new
        // URL
        // LOGGER.info("Exception not found resource");

    }
    if (resource == null) {
        // LOGGER.info("Resource Null start create new resource");
        resource = rep.createNewResource(curURI);
        // isNew=true;
    }
    if (resource == null) {
        // LOGGER.info("Error, resource is null");
        // Set the return error
        // Unprocessable Entity (see
        // http://www.webdav.org/specs/rfc2518.html#status.code.extensions.to.http11)
        this.setHTTPStatus(422);
    } else {
        if (relockToken != null) {
            li = lm.relock(resource, relockToken, TimeOutValue);
            if (li == null) {
                String eString = "Relock failed for " + relockToken;
                LOGGER.debug(eString);
                this.setErrorMessage(eString, 412); // Precondition failed
                status = 412;
            } else {
                LOGGER.debug("successful relock for " + relockToken + ", new Token:" + li.getToken());
                status = HttpServletResponse.SC_OK;
            }
        }
        if (status >= 400) {
            this.setHTTPStatus(status);
            HttpServletResponse resp = this.getResp();
            resp.setStatus(status);
            return;
        }
        try {
            instream = this.getReq().getInputStream();
            out = resource.getOutputStream();
        } catch (Exception e) {
            LOGGER.error("Input/Output stream creation failed", e);
            success = false;
            this.setErrorMessage("Input/Output stream creation failed in PUT for " + curURI, 501);
        }
        if (success) {
            try {
                int read = 0;
                byte[] bytes = new byte[2 * 2048]; // TODO: are 2 KB blocks
                // the right size?
                while ((read = instream.read(bytes)) != -1) {
                    // LOGGER.info("Read total"+ new
                    // Integer(read).toString() +" bytes");
                    out.write(bytes, 0, read);
                    // LOGGER.info("Write  total"+ new
                    // Integer(read).toString() +" bytes");
                }

            } catch (Exception ex) {
                LOGGER.error(ex);
            } finally {
                try {
                    if (instream != null) {
                        instream.close();
                        // LOGGER.info("istream successfully closed");
                    }
                } catch (Exception finalE) {
                    // Not a fatal error
                    LOGGER.error("Put stream closing failed", finalE);
                }

                try {
                    if (out != null) {
                        // LOGGER.info("out closed");
                        out.flush();
                        // LOGGER.info("Output stream flushed");
                        out.close();
                        // LOGGER.info("Output stream closed");
                    }
                } catch (Exception outE) {
                    // Success is false!
                    LOGGER.error("closing of output stream (and saving) failed", outE);
                    this.setErrorMessage("closing of output stream (and saving) failed for" + curURI, 501);
                    success = false;
                }
            }
        }
    }
    if (this.getReq().getContentLength() == 0) {
        this.setHTTPStatus(HttpServletResponse.SC_CREATED);
        HttpServletResponse resp = this.getResp();
        resp.setStatus(HttpServletResponse.SC_CREATED);
        return;
    }
    this.setHTTPStatus(HttpServletResponse.SC_OK);
    HttpServletResponse resp = this.getResp();
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:eu.stratosphere.nephele.jobmanager.web.QosStatisticsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*w  ww. j av  a 2s . c  o  m*/
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json");

        JSONObject jobs = new JSONObject();
        JobID job;
        long startTimestamp = -1;

        if (req.getParameter("job") != null && !req.getParameter("job").isEmpty())
            job = JobID.fromHexString(req.getParameter("job"));
        else
            job = getLastCreatedJob();

        if (req.getParameter("startTimestamp") != null && !req.getParameter("startTimestamp").isEmpty())
            startTimestamp = Long.parseLong(req.getParameter("startTimestamp"));

        for (JobID id : jobStatistics.keySet()) {
            JSONObject jobDetails = jobStatistics.get(id).getJobMetadata();

            if (job != null && job.equals(id)) {
                if (startTimestamp > 0)
                    jobStatistics.get(id).getStatistics(jobDetails, startTimestamp);
                else
                    jobStatistics.get(id).getStatistics(jobDetails);
            }

            jobs.put(id.toString(), jobDetails);
        }

        JSONObject result = new JSONObject();
        if (job != null && jobStatistics.containsKey(job)) {
            result.put("currentJob", job);
            result.put("refreshInterval", jobStatistics.get(job).getRefreshInterval());
            result.put("maxEntriesCount", jobStatistics.get(job).getMaxEntriesCount());
        } else {
            result.put("refreshInterval", INITIAL_REFRESH_INTERVAL);
            result.put("maxEntriesCount", 0);
        }
        result.put("jobs", jobs);
        result.write(resp.getWriter());

    } catch (JSONException e) {
        LOG.error("JSON Error: " + e.getMessage(), e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.setContentType("application/json");
        resp.getWriter().println("{ status: \"internal error\", message: \"" + e.getMessage() + "\" }");
    }
}

From source file:com.graphaware.module.resttest.RestTestApi.java

@RequestMapping(value = "/assertSubgraph", method = RequestMethod.POST)
@ResponseBody/*  ww w . j av a2 s  .  c  o  m*/
public String assertSubgraph(@RequestBody RestTestRequest request, HttpServletResponse response)
        throws IOException {
    if (request.getCypher() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cypher statement must be provided");
    }

    try {
        GraphUnit.assertSubgraph(database, request.getCypher(), resolveInclusionPolicies(request));
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (AssertionError error) {
        response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
        return error.getMessage();
    }
}

From source file:com.liusoft.dlog4j.xml.RSSFetcher.java

/**
 * ??//w  ww  . j  av  a2  s  .c  o  m
 * @param type
 * @param url
 * @return
 * @throws IOException 
 * @throws HttpException 
 * @throws SAXException 
 * @throws ParseException 
 */
private static Channel fetchChannelViaHTTP(String url) throws HttpException, IOException, SAXException {
    Digester parser = new XMLDigester();
    GetMethod get = new GetMethod(url);
    //get.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; zh-cn) Opera 8.52");
    try {
        http_client.executeMethod(get);
        if (get.getStatusCode() == HttpServletResponse.SC_OK) {
            Charset cs = null;
            Header header_cs = getResponseHeader(get, "Content-Type");
            if (header_cs == null) {
                cs = Charset.forName(get.getResponseCharSet());
            } else {
                String content_type = header_cs.getValue().toLowerCase();
                try {
                    Object[] values = content_type_parser.parse(content_type);
                    cs = Charset.forName((String) values[1]);
                } catch (ParseException e) {
                    URL o_url = new URL(url);
                    String host = o_url.getHost();
                    Iterator hosts = charsets.keySet().iterator();
                    while (hosts.hasNext()) {
                        String t_host = (String) hosts.next();
                        if (host.toLowerCase().endsWith(t_host)) {
                            cs = Charset.forName((String) charsets.get(t_host));
                            break;
                        }
                    }
                    if (cs == null)
                        cs = default_charset;

                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(), cs));

            char[] cbuf = new char[1];
            int read_idx = 1;
            do {
                rd.mark(read_idx++);
                if (rd.read(cbuf) == -1)
                    break;
                if (cbuf[0] != '<')
                    continue;
                rd.reset();
                break;
            } while (true);
            return (Channel) parser.parse(rd);
        } else {
            log.error("Fetch RSS from " + url + " failed, code=" + get.getStatusCode());
        }
    } finally {
        get.releaseConnection();
    }
    return null;
}

From source file:org.jboss.as.test.clustering.cluster.web.NonHaWebSessionPersistenceTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT_1)/*  w  w w .  j  a  va 2  s . c o  m*/
public void testSessionPersistence(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL)
        throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();

    String url = baseURL.toString() + "simple";

    try {
        HttpResponse response = client.execute(new HttpGet(url));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet(url));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        stop(CONTAINER_SINGLE);
        start(CONTAINER_SINGLE);

        response = client.execute(new HttpGet(url));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals("Session passivation was configured but session was lost after restart.", 3,
                Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handlePostPatchPut(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {//from   w  w w  . ja  va2 s . co  m
        int desiredResponseCode = parseDesiredResponseCode(target);
        response.setStatus(desiredResponseCode);
        response.setContentType(CONTENT_TYPE);

        if (desiredResponseCode == HttpServletResponse.SC_OK) {
            String requestBody = IOUtils.toString(request.getInputStream());
            response.getWriter().write(requestBody);
        }
    } catch (Exception e) {
        handleException(e, response);
    }
}