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:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter(ACTION_PARAM_NAME);

    if (action.equals(ACTION_LIST_VALUE)) {
        GregorianCalendar cal = new GregorianCalendar();

        File[] files = destinationDir.listFiles();
        Arrays.<File>sort(files, FILE_SORTER);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(CONTENT_TYPE_PLAIN);

        PrintWriter writer = resp.getWriter();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].getName().endsWith(".jar")) {
                continue;
            }//from  w w  w.  j ava  2  s  .  c o m

            cal.setTimeInMillis(files[i].lastModified());
            writer.println(files[i].getName() + '\t' + (cal.get(GregorianCalendar.MONTH) + 1) + '/'
                    + cal.get(GregorianCalendar.DAY_OF_MONTH) + '/' + cal.get(GregorianCalendar.YEAR) + ' '
                    + cal.get(GregorianCalendar.HOUR_OF_DAY) + ':' + cal.get(GregorianCalendar.MINUTE) + ':'
                    + cal.get(GregorianCalendar.SECOND));
        }
    } else if (action.equals(ACTION_DELETE_VALUE)) {
        String filename = req.getParameter(FILENAME_PARAM_NAME);

        if (filename == null || filename.length() == 0) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            File f = new File(destinationDir, filename);
            if (!f.exists() || f.isDirectory()) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
            f.delete();
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.thoughtworks.go.util.HttpService.java

public int download(String url, FetchHandler handler) throws IOException {
    HttpGet toGet = null;//  w w  w.j a va 2 s.  c  o m
    InputStream is = null;
    try {
        toGet = httpClientFactory.createGet(url);
        PerfTimer timer = PerfTimer.start(String.format("Downloading from url [%s]", url));
        try (CloseableHttpResponse response = execute(toGet)) {
            timer.stop();
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == HttpServletResponse.SC_OK) {
                if (response.getEntity() != null) {
                    is = response.getEntity().getContent();
                }
                handler.handle(is);
            }
            return statusCode;
        }
    } catch (IOException e) {
        LOGGER.error("Error while downloading [{}]", url, e);
        throw e;
    } finally {
        IOUtils.closeQuietly(is);
        if (toGet != null) {
            toGet.releaseConnection();
        }
    }
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom GET by calling handler and writing results to response.
 *//*from   w ww .j  a v a 2 s  . c  o  m*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isAtomServiceURI(areq)) {
                // return an Atom Service document
                AtomService service = handler.getAtomService(areq);
                Document doc = service.serviceToDocument();
                res.setContentType("application/atomsvc+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(doc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCategoriesURI(areq)) {
                Categories cats = handler.getCategories(areq);
                res.setContentType("application/xml");
                Writer writer = res.getWriter();
                Document catsDoc = new Document();
                catsDoc.setRootElement(cats.categoriesToElement());
                XMLOutputter outputter = new XMLOutputter();
                outputter.output(catsDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isCollectionURI(areq)) {
                // return a collection
                Feed col = handler.getCollection(areq);
                col.setFeedType(FEED_TYPE);
                WireFeedOutput wireFeedOutput = new WireFeedOutput();
                Document feedDoc = wireFeedOutput.outputJDom(col);
                res.setContentType("application/atom+xml; charset=utf-8");
                Writer writer = res.getWriter();
                XMLOutputter outputter = new XMLOutputter();
                outputter.setFormat(Format.getPrettyFormat());
                outputter.output(feedDoc, writer);
                writer.close();
                res.setStatus(HttpServletResponse.SC_OK);
            } else if (handler.isEntryURI(areq)) {
                // return an entry
                Entry entry = handler.getEntry(areq);
                if (entry != null) {
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");
                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(entry, writer);
                    writer.close();
                } else {
                    res.setStatus(HttpServletResponse.SC_NOT_FOUND);
                }
            } else if (handler.isMediaEditURI(areq)) {
                AtomMediaResource entry = handler.getMediaResource(areq);
                res.setContentType(entry.getContentType());
                res.setContentLength((int) entry.getContentLength());
                Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream());
                res.getOutputStream().flush();
                res.getOutputStream().close();
            } else {
                res.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing GET", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing GET", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:org.jboss.as.test.clustering.cluster.singleton.SingletonTestCase.java

@Test
public void testSingletonService(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    // Needed to be able to inject ArquillianResource
    stop(CONTAINER_2);//from www  .  j a va  2  s. c  o m

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    // URLs look like "http://IP:PORT/singleton/service"
    URI defaultURI1 = MyServiceServlet.createURI(baseURL1, MyService.DEFAULT_SERVICE_NAME);
    URI defaultURI2 = MyServiceServlet.createURI(baseURL2, MyService.DEFAULT_SERVICE_NAME);

    log.info("URLs are: " + defaultURI1 + ", " + defaultURI2);

    URI quorumURI1 = MyServiceServlet.createURI(baseURL1, MyService.QUORUM_SERVICE_NAME);
    URI quorumURI2 = MyServiceServlet.createURI(baseURL2, MyService.QUORUM_SERVICE_NAME);

    try {
        HttpResponse response = client.execute(new HttpGet(defaultURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader("node"));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_2);

        response = client.execute(new HttpGet(defaultURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(defaultURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        stop(CONTAINER_2);

        response = client.execute(new HttpGet(defaultURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader("node"));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_2);

        response = client.execute(new HttpGet(defaultURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(defaultURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        stop(CONTAINER_1);

        response = client.execute(new HttpGet(defaultURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(NODE_2, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader("node"));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_1);

        response = client.execute(new HttpGet(defaultURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(defaultURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(quorumURI2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(MyServiceActivator.PREFERRED_NODE, response.getFirstHeader("node").getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.homesnap.webserver.GroupRestAPITest.java

@Test
public void test7OnStatus() {
    // Test to get a specific group
    JSONObject group = getRequestJSONObject("/house/groups/1?param=param");
    // Test group 1
    testGroup1Bis(group);/*from   ww w .j a va 2  s  . c o m*/

    group = getRequestJSONObject("/house/groups/group?id=10&param=param");
    // Test group 10
    testGroup10(group);

    putRequestJSONObject("/house/groups/1?param=param", createGroup1(), HttpServletResponse.SC_OK);
    putRequestJSONObject("/house/groups/group?id=1&param=param", createGroup1(), HttpServletResponse.SC_OK);

    postRequestJSONObject("/house/groups/1/21", createController21(), HttpServletResponse.SC_CREATED);
    JSONObject jo = getRequestJSONObject("/house/groups/1/controller?id=21&param=param");
    testController21(jo);

    jo = getRequestJSONObject("/house/groups/1/21?param=param");
    testController21(jo);

    testController21(jo);

    deleteRequestJSONObject("/house/groups/1?param=param", HttpServletResponse.SC_OK);
    deleteRequestJSONObject("/house/groups/group?id=1&param=param", HttpServletResponse.SC_NOT_ACCEPTABLE);
}

From source file:eu.trentorise.smartcampus.permissionprovider.auth.google.GoogleController.java

/**
 * This rest web service is the one that google called after login (callback
 * url). First it retrieve code and token that google sends back. It checks
 * if code and token are not null, then if token is the same that was saved
 * in session. If it is not response status is UNAUTHORIZED, otherwise it
 * retrieves user data. If user is not already saved in db, then user is
 * added in db, iff email is not already used, otherwise it sends an
 * UNAUTHORIZED status and redirect user to home page without authenticating
 * him/her. If it is all ok, then it authenticates user in spring security
 * and create cookie user. Then redirects authenticated user to home page
 * where user can access protected resources.
 * //w w  w  . java2 s  . c  o  m
 * @param request
 *            : instance of {@link HttpServletRequest}
 * @param response
 *            : instance of {@link HttpServletResponse}
 * @return redirect to home page
 */
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) {

    String code = request.getParameter("code");
    String token = request.getParameter("state");
    String sessionStateToken = "";
    if (request.getSession().getAttribute(SESSION_ATTR_STATE) != null) {
        sessionStateToken = request.getSession().getAttribute(SESSION_ATTR_STATE).toString();
    }

    // compare state token in session and state token in response of google
    // if equals return to home
    // if not error page
    if ((code == null || token == null) && (!token.equals(sessionStateToken))) {
        logger.error("Error in google authentication flow");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return "";
    } else {
        try {
            GoogleUser userInfo = auth.getUserInfoJson(code);
            response.setStatus(HttpServletResponse.SC_OK);
            request.getSession().setAttribute(GoogleAuthHelper.SESSION_GOOGLE_CHECK, "true");
            return String.format(
                    "redirect:/eauth/google?target=%s&OIDC_CLAIM_email=%s&OIDC_CLAIM_given_name=%s&OIDC_CLAIM_family_name=%s",
                    URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"),
                    userInfo.getEmail(), userInfo.getGivenName(), userInfo.getFamilyName());

        } catch (IOException e) {
            logger.error("IOException .. Problem in reading user data.", e);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    return "redirect:/";
}

From source file:com.attribyte.essem.DefaultResponseGenerator.java

private void generateGraph(JsonNode responseObject, HttpServletResponse response) throws IOException {
    response.setContentType(JSON_CONTENT_TYPE_HEADER);
    response.setStatus(HttpServletResponse.SC_OK);
    response.getOutputStream().write(responseObject.toString().getBytes("UTF-8"));
    response.getOutputStream().flush();/*from  ww w.j  av  a 2 s .c om*/
}

From source file:org.apache.servicemix.http.security.HttpSecurityTest.java

public void testWSSec() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileUtil.copyInputStream(getClass().getResourceAsStream("request.xml"), out);
    String request = out.toString();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://localhost:8192/WSSec/");
    try {//from   ww  w  .  j  a va2 s  .  c  om
        method.setDoAuthentication(true);
        method.setRequestEntity(new StringRequestEntity(request));
        int state = client.executeMethod(method);

        String str = method.getResponseBodyAsString();
        log.info(str);
        if (state != HttpServletResponse.SC_OK && state != HttpServletResponse.SC_ACCEPTED) {
            throw new IllegalStateException("Http status: " + state);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:com.amazon.speech.speechlet.servlet.SpeechletServlet.java

/**
 * Handles a POST request. Based on the request parameters, invokes the right method on the
 * {@code SpeechletV2}.//  www  .jav a  2s. c o m
 *
 * @param request
 *            the object that contains the request the client has made of the servlet
 * @param response
 *            object that contains the response the servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet handles the request
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    byte[] serializedSpeechletRequest = IOUtils.toByteArray(request.getInputStream());
    byte[] outputBytes = null;

    try {
        if (disableRequestSignatureCheck) {
            log.warn("Warning: Speechlet request signature verification has been disabled!");
        } else {
            // Verify the authenticity of the request by checking the provided signature &
            // certificate.
            SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest,
                    request.getHeader(Sdk.SIGNATURE_REQUEST_HEADER),
                    request.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER));
        }

        outputBytes = speechletRequestHandler.handleSpeechletCall(speechlet, serializedSpeechletRequest);
    } catch (SpeechletRequestHandlerException | SecurityException ex) {
        int statusCode = HttpServletResponse.SC_BAD_REQUEST;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    } catch (Exception ex) {
        int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    }

    // Generate JSON and send back the response
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    try (final OutputStream out = response.getOutputStream()) {
        response.setContentLength(outputBytes.length);
        out.write(outputBytes);
    }
}