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:com.epam.wilma.test.server.PerformanceTestHandler.java

@Override
public void handle(final String path, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (PATH_TO_HANDLE.equals(path)) {
        double rnd = random.nextDouble();
        byte[] responseBodyAsBytes;
        if (rnd > 0.98) {
            responseBodyAsBytes = xmlMaxAsBytes;
        } else if (rnd > 0.3) {
            responseBodyAsBytes = xmlLargeAsBytes;
        } else if (rnd > 0.1) {
            responseBodyAsBytes = xmlSmallAsBytes;
        } else {/*w w  w  . j  a v a  2  s. c o m*/
            responseBodyAsBytes = xmlMinAsBytes;
        }
        response.setContentType("application/fastinfoset");
        response.setCharacterEncoding("UTF-8");
        response.getOutputStream().write(responseBodyAsBytes);
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        response.getOutputStream().close();
    }
}

From source file:otherpackage.MyConfigurerTests.java

@Test
public void customConfiguerCustomizeDisablesCsrf() throws Exception {
    loadContext(ConfigCustomize.class);
    request.setPathInfo("/public/something");
    request.setMethod("POST");

    springSecurityFilterChain.doFilter(request, response, chain);

    assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}

From source file:ch.entwine.weblounge.test.harness.content.JSONActionTest.java

/**
 * {@inheritDoc}/*from   w w w  . j a va  2s .c o m*/
 * 
 * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String)
 */
@Override
public void execute(String serverUrl) throws Exception {
    logger.info("Preparing test of greeter action");

    String requestUrl = UrlUtils.concat(serverUrl, "greeting/index.json");

    // Load the test data
    Map<String, String> greetings = TestSiteUtils.loadGreetings();
    Set<String> languages = greetings.keySet();

    // Prepare the request
    logger.info("Testing greeter action's json output");
    logger.info("Sending requests to {}", requestUrl);

    for (String language : languages) {
        String greeting = greetings.get(language);
        HttpGet request = new HttpGet(requestUrl);
        String[][] params = new String[][] { { "language", language } };

        // Send and the request and examine the response
        logger.info("Sending request to {} for {} greeting", request.getURI(), language);
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = TestUtils.request(httpClient, request, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

            ObjectMapper jsonMapper = new ObjectMapper();
            TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
            };

            // Find the content encoding
            Assert.assertNotNull(response.getFirstHeader("Content-Type"));
            Assert.assertNotNull(
                    response.getFirstHeader("Content-Type").getElements()[0].getParameterByName("charset"));
            String charset = response.getFirstHeader("Content-Type").getElements()[0]
                    .getParameterByName("charset").getValue();

            String responseJson = EntityUtils.toString(response.getEntity(), charset);
            HashMap<String, Object> json = jsonMapper.readValue(responseJson, typeRef);

            String expectedGeetingEncoded = new String(greeting.getBytes(charset), charset);
            String actualGeetingEncoded = new String(json.get(language).toString().getBytes(charset), charset);
            Assert.assertEquals(expectedGeetingEncoded, actualGeetingEncoded);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:org.osmsurround.ae.amenity.AmenityService.java

public void deleteAmenity(Node.OsmType osmType, long nodeId) {
    HttpResponse httpResponse = osmDeleteRequest.execute(getNode(nodeId));
    if (httpResponse.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
        internalDataService.deleteInternalData(osmType, nodeId);
    } else {/*from   w  w  w  . j ava  2s .c o m*/
        throw RequestUtils.createExceptionFromHttpResponse(httpResponse);
    }
}

From source file:com.carolinarollergirls.scoreboard.jetty.XmlScoreBoardServlet.java

protected void set(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
    XmlListener listener = getXmlListenerForRequest(request);
    if (null == listener) {
        registrationKeyNotFound(request, response);
        return;/* www  . jav a2 s  . c  o  m*/
    }

    Document requestDocument = editor.toDocument(request.getInputStream());
    if (null == requestDocument) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (debugSet)
        ScoreBoardManager.printMessage(
                "SET from " + listener.getKey() + "\n" + rawXmlOutputter.outputString(requestDocument));

    scoreBoardModel.getXmlScoreBoard().mergeDocument(requestDocument);

    response.setContentType("text/plain");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:foo.domaintest.email.Emailer.java

public void send(String from, String to, String body, String inReplyTo, String references) {
    try {//  www . ja  v a  2  s .c o m
        HTTPRequest request = new HTTPRequest(new URL(SENDGRID_SEND_URL), HTTPMethod.POST);
        request.addHeader(new HTTPHeader(CONTENT_TYPE, FORM_UTF8_MIME));
        request.setPayload(encodeQuery(
                new ImmutableMap.Builder<String, String>().put("api_user", apiUser).put("api_key", apiKey)
                        .put("to", to).put("from", from).put("subject", "Automated testing service response")
                        .put("text", isNullOrEmpty(body) ? " " : body) // SendGrid rejects an empty body.
                        .put("headers",
                                toJSONString(filterValues(ImmutableMap.of("In-Reply-To", nullToEmpty(inReplyTo),
                                        "References", nullToEmpty(references)), not(equalTo("")))))
                        .build()).getBytes(UTF_8));
        HTTPResponse response = getURLFetchService().fetch(request);
        if (response.getResponseCode() != HttpServletResponse.SC_OK) {
            logger.warning(String.format("%d: %s", response.getResponseCode(),
                    new String(response.getContent(), UTF_8)));
        }
        metrics.addActivity("autoreply");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:hr.diskobolos.controller.SportController.java

/**
 * REST service responsible for editing sport data
 *
 * @param sportDto/*from   ww  w.  j a  v a  2 s.c o  m*/
 * @param request
 * @param response
 * @return
 * @throws JSONException
 */
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
public String editSportData(@RequestBody SportDto sportDto, HttpServletRequest request,
        HttpServletResponse response) throws JSONException {
    try {
        Sport sport = mapSportDtoToSportModelObject(sportDto);
        sportService.update(sport);
        if (sportDto.getRemovedNomenclatureItems() != null) {
            nomenclatureOfSportService.delete(sportDto.getRemovedNomenclatureItems());
        }
        response.setStatus(HttpServletResponse.SC_OK);

        return new JSONObject().put("result", 200).toString();
    } catch (Exception e) {
        logger.error("Error during editing sport data: ", e.getMessage());
        return ErrorHandlerUtils.handleAjaxError(request, response);
    }
}

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

private static void assertValue(HttpClient client, URI uri, int value) throws IOException {
    HttpResponse response = client.execute(new HttpGet(uri));
    try {//from  w  w  w  . j av  a 2s . c  o  m
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(value,
                Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:io.fabric8.agent.DownloadManagerTest.java

@Test
public void testDownloadUsingNonAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from  w  ww .  j a v  a2s.  c o  m
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getOutputStream().write(new byte[] { 0x42 });
            response.getOutputStream().close();
        }
    });
    server.start();

    Properties custom = new Properties();
    custom.setProperty("org.ops4j.pax.url.mvn.proxySupport", "true");
    String settings = createMavenSettingsWithProxy(server.getConnectors()[0].getLocalPort());
    DownloadManager dm = createDownloadManager("http://relevant.not/maven2@id=central", settings, custom);

    try {
        final CountDownLatch latch = new CountDownLatch(1);
        DownloadFuture df = dm.download("mvn:x.y/z/1.0");
        df.addListener(new FutureListener<DownloadFuture>() {
            @Override
            public void operationComplete(DownloadFuture future) {
                latch.countDown();
            }
        });

        latch.await(30, TimeUnit.SECONDS);
        assertNotNull(df.getUrl());
        assertNotNull(df.getFile());
        assertEquals("z-1.0.jar", df.getFile().getName());
        LOG.info("Downloaded URL={}, FILE={}", df.getUrl(), df.getFile());
    } finally {
        server.stop();
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.GraphServlet.java

@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);

    if (mediaType != null) {
        // Preflight CORS support
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET");
        response.setIntHeader("Access-Control-Max-Age", 60 * 60 * 24);
        response.setContentType(mediaType + ";charset=utf-8");
        response.setContentLength(0);//ww w .j a va  2  s  . c o m
    } else {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}