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:org.opencastproject.distribution.hls.HLSDistributionServiceImplTest.java

@Before
public void setUp() throws Exception {
    File mediaPackageRoot = new File(getClass().getResource("/mediapackage.xml").toURI()).getParentFile();
    MediaPackageBuilder builder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
    builder.setSerializer(new DefaultMediaPackageSerializerImpl(mediaPackageRoot));
    InputStream is = null;/*from   w w  w.  j  a v a  2  s.co  m*/
    try {
        is = getClass().getResourceAsStream("/mediapackage.xml");
        mp = builder.loadFromXml(is);
    } finally {
        IOUtils.closeQuietly(is);
    }

    distributionRoot = new File(mediaPackageRoot, "static");
    service = new HLSDistributionServiceImpl();

    StatusLine statusLine = EasyMock.createNiceMock(StatusLine.class);
    EasyMock.expect(statusLine.getStatusCode()).andReturn(HttpServletResponse.SC_OK).anyTimes();
    EasyMock.replay(statusLine);

    HttpResponse response = EasyMock.createNiceMock(HttpResponse.class);
    EasyMock.expect(response.getStatusLine()).andReturn(statusLine).anyTimes();
    EasyMock.replay(response);

    TrustedHttpClient httpClient = EasyMock.createNiceMock(TrustedHttpClient.class);
    EasyMock.expect(httpClient.execute((HttpUriRequest) EasyMock.anyObject())).andReturn(response).anyTimes();
    EasyMock.replay(httpClient);

    User anonymous = new User("anonymous", DEFAULT_ORGANIZATION_ID,
            new String[] { DEFAULT_ORGANIZATION_ANONYMOUS });
    UserDirectoryService userDirectoryService = EasyMock.createMock(UserDirectoryService.class);
    EasyMock.expect(userDirectoryService.loadUser((String) EasyMock.anyObject())).andReturn(anonymous)
            .anyTimes();
    EasyMock.replay(userDirectoryService);
    service.setUserDirectoryService(userDirectoryService);

    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock
            .createMock(OrganizationDirectoryService.class);
    EasyMock.expect(organizationDirectoryService.getOrganization((String) EasyMock.anyObject()))
            .andReturn(organization).anyTimes();
    EasyMock.replay(organizationDirectoryService);
    service.setOrganizationDirectoryService(organizationDirectoryService);

    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.replay(securityService);
    service.setSecurityService(securityService);

    serviceRegistry = new ServiceRegistryInMemoryImpl(service, securityService, userDirectoryService,
            organizationDirectoryService);
    service.setServiceRegistry(serviceRegistry);
    service.setTrustedHttpClient(httpClient);
    service.distributionDirectory = distributionRoot;
    service.serviceUrl = UrlSupport.DEFAULT_BASE_URL;
    Workspace workspace = EasyMock.createNiceMock(Workspace.class);
    service.setWorkspace(workspace);

    EasyMock.expect(workspace.get((URI) EasyMock.anyObject()))
            .andReturn(new File(mediaPackageRoot, "media.mov"));
    EasyMock.expect(workspace.get((URI) EasyMock.anyObject()))
            .andReturn(new File(mediaPackageRoot, "dublincore.xml"));
    EasyMock.expect(workspace.get((URI) EasyMock.anyObject()))
            .andReturn(new File(mediaPackageRoot, "mpeg7.xml"));
    EasyMock.expect(workspace.get((URI) EasyMock.anyObject()))
            .andReturn(new File(mediaPackageRoot, "attachment.txt"));
    EasyMock.replay(workspace);
}

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

/**
 * Test simple graceful shutdown failover:
 * <p/>//from  ww w.j  av  a2  s .  co m
 * 1/ Start 2 containers and deploy <distributable/> webapp.
 * 2/ Query first container creating a web session.
 * 3/ Shutdown first container.
 * 4/ Query second container verifying sessions got replicated.
 * 5/ Bring up the first container.
 * 6/ Query first container verifying that updated sessions replicated back.
 *
 * @throws IOException
 * @throws InterruptedException
 * @throws URISyntaxException
 */
@Test
public void testGracefulSimpleFailover(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

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

    String url1 = baseURL1.toString() + "simple";
    String url2 = baseURL2.toString() + "simple";

    try {
        HttpResponse response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Gracefully shutdown the 1st container.
        stop(CONTAINER_1);

        // Now check on the 2nd server

        // Note that this DOES rely on the fact that both servers are running on the "same" domain,
        // which is '127.0.0.0'. Otherwise you will have to spoof cookies. @Rado

        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 3,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do one more check.
        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_1);

        // Lets wait for the cluster to update membership and tranfer state.

        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was brough up.", 5,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(6, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:ch.systemsx.cisd.openbis.generic.client.web.server.UploadServiceServlet.java

private final void sendResponse(final HttpServletResponse response, final String textOrNull) {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    if (textOrNull != null) {
        try {// w w w  . j a v a  2 s  .  co  m
            response.getWriter().write(textOrNull);
        } catch (final IOException ex) {
            throw new IOExceptionUnchecked(ex);
        }
    }
}

From source file:com.amazon.dtasdk.v2.servlets.InstantAccessServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {/*from  w  ww. j a  va 2 s.  c  om*/
        Request req = new Request(request);

        if (!signer.verify(req, getCredentialStore())) {
            throw new SigningException("Request validation failed.");
        }

        String requestBody = req.getBody();

        // deserialize the content to a InstantAccessRequest object so we can check which operation is going
        // to be called
        InstantAccessRequest iaRequest = serializer.decode(requestBody, InstantAccessRequest.class);

        // process the request according to the operation
        InstantAccessResponse<?> iaResponse = processOperation(iaRequest.getOperation(), requestBody);

        response.setStatus(HttpServletResponse.SC_OK);
        response.getOutputStream().write(serializer.encode(iaResponse).getBytes(CHARSET));
    } catch (IOException e) {
        log.error("Unable to read the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (SigningException e) {
        log.error("Unable to verify the request against the credential store.", e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } catch (SerializationException e) {
        log.error("Serialization error.", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        log.error("Unable to process the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.opencastproject.distribution.download.DownloadDistributionServiceImplTest.java

@Before
public void setUp() throws Exception {
    final File mediaPackageRoot = new File(getClass().getResource("/mediapackage.xml").toURI()).getParentFile();
    MediaPackageBuilder builder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
    builder.setSerializer(new DefaultMediaPackageSerializerImpl(mediaPackageRoot));
    InputStream is = null;/*from w  w  w.j a  v  a2s. c om*/
    try {
        is = getClass().getResourceAsStream("/mediapackage.xml");
        mp = builder.loadFromXml(is);
    } finally {
        IOUtils.closeQuietly(is);
    }

    distributionRoot = new File(mediaPackageRoot, "static");
    service = new DownloadDistributionServiceImpl();

    StatusLine statusLine = EasyMock.createNiceMock(StatusLine.class);
    EasyMock.expect(statusLine.getStatusCode()).andReturn(HttpServletResponse.SC_OK).anyTimes();
    EasyMock.replay(statusLine);

    HttpResponse response = EasyMock.createNiceMock(HttpResponse.class);
    EasyMock.expect(response.getStatusLine()).andReturn(statusLine).anyTimes();
    EasyMock.replay(response);

    TrustedHttpClient httpClient = EasyMock.createNiceMock(TrustedHttpClient.class);
    EasyMock.expect(httpClient.execute((HttpUriRequest) EasyMock.anyObject())).andReturn(response).anyTimes();
    EasyMock.replay(httpClient);

    User anonymous = new User("anonymous", DefaultOrganization.DEFAULT_ORGANIZATION_ID,
            new String[] { DefaultOrganization.DEFAULT_ORGANIZATION_ANONYMOUS });
    UserDirectoryService userDirectoryService = EasyMock.createMock(UserDirectoryService.class);
    EasyMock.expect(userDirectoryService.loadUser((String) EasyMock.anyObject())).andReturn(anonymous)
            .anyTimes();
    EasyMock.replay(userDirectoryService);
    service.setUserDirectoryService(userDirectoryService);

    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock
            .createMock(OrganizationDirectoryService.class);
    EasyMock.expect(organizationDirectoryService.getOrganization((String) EasyMock.anyObject()))
            .andReturn(organization).anyTimes();
    EasyMock.replay(organizationDirectoryService);
    service.setOrganizationDirectoryService(organizationDirectoryService);

    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.replay(securityService);
    service.setSecurityService(securityService);

    serviceRegistry = new ServiceRegistryInMemoryImpl(service, securityService, userDirectoryService,
            organizationDirectoryService);
    service.setServiceRegistry(serviceRegistry);
    service.setTrustedHttpClient(httpClient);
    service.distributionDirectory = distributionRoot;
    service.serviceUrl = UrlSupport.DEFAULT_BASE_URL;

    final Workspace workspace = EasyMock.createNiceMock(Workspace.class);
    service.setWorkspace(workspace);

    EasyMock.expect(workspace.get((URI) EasyMock.anyObject())).andAnswer(new IAnswer<File>() {
        @Override
        public File answer() throws Throwable {
            final URI uri = (URI) EasyMock.getCurrentArguments()[0];
            final String[] pathElems = uri.getPath().split("/");
            final String file = pathElems[pathElems.length - 1];
            return new File(mediaPackageRoot, file);
        }
    }).anyTimes();
    EasyMock.replay(workspace);
}

From source file:io.airlift.http.server.TestHttpServerProvider.java

@Test
public void testHttp() throws Exception {
    createServer();/*from  w w w. j  av  a 2 s. c  om*/
    server.start();

    try (JettyHttpClient httpClient = new JettyHttpClient()) {
        StatusResponse response = httpClient.execute(prepareGet().setUri(httpServerInfo.getHttpUri()).build(),
                createStatusResponseHandler());

        assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK);
    }
}

From source file:core.NiprSyncController.java

@CrossOrigin
@RequestMapping(value = "/ping", method = RequestMethod.GET)
public void ping(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Licensing+ app is running.");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:io.wcm.caravan.pipeline.impl.operators.ResponseHandlingOperator.java

@Override
public Subscriber<? super CaravanHttpResponse> call(Subscriber<? super JsonPipelineOutput> subscriber) {
    return new Subscriber<CaravanHttpResponse>() {

        @Override/* w w  w.j  av  a2 s. c  o  m*/
        public void onCompleted() {
            subscriber.onCompleted();
        }

        @Override
        public void onError(Throwable e) {
            Exceptions.throwIfFatal(e);

            int statusCode = 500;
            if (e instanceof IllegalResponseRuntimeException) {
                statusCode = ((IllegalResponseRuntimeException) e).getResponseStatusCode();
            }

            JsonPipelineInputException jsonPipelineInputException = new JsonPipelineInputException(statusCode,
                    "Failed to GET " + request.getUrl(), e).setReason(e.getMessage());
            subscriber.onError(jsonPipelineInputException);
        }

        @Override
        public void onNext(CaravanHttpResponse response) {
            try (Body body = response.body()) {
                final int statusCode = response.status();
                log.debug("received {} response ({}) with from {},\n{}", statusCode, response.reason(),
                        request.getUrl(), request.getCorrelationId());
                if (statusCode == HttpServletResponse.SC_OK) {

                    JsonNode payload = JacksonFunctions.stringToNode(body.asString());
                    int maxAge = NumberUtils.toInt(response.getCacheControl().get("max-age"), -1);
                    JsonPipelineOutput model = new JsonPipelineOutputImpl(payload, ImmutableList.of(request))
                            .withMaxAge(maxAge);

                    subscriber.onNext(model);
                } else {
                    String msg = "Request for " + request.getUrl() + " failed with HTTP status code: "
                            + statusCode + " (" + response.reason() + ")" + ", " + request.getCorrelationId();

                    if (statusCode / 100 == 4) {
                        log.info(msg);
                    } else {
                        log.warn(msg);
                    }

                    JsonPipelineInputException pipelineInputException = new JsonPipelineInputException(
                            statusCode, msg).setReason(response.reason());
                    subscriber.onError(pipelineInputException);
                }
            } catch (IOException ex) {
                JsonPipelineInputException pipelineInputException = new JsonPipelineInputException(500,
                        "Failed to read JSON response from " + request.getUrl(), ex)
                                .setReason(response.reason());
                subscriber.onError(pipelineInputException);
            }
        }
    };
}

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

/**
 * Handle hand shake.//from   ww  w .j  av a 2 s .  co  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.excella.deploy.agent.core.DynamicCommandServlet.java

/**
 * COMMENT DynamicCommandServlet.fail()/*  w ww. java  2s  .  co m*/
 *
 * @param command
 * @param e
 * @param request
 * @param response
 */
protected void fail(Command command, Exception cause, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        log.debug("Attempting to respond with a failure...");
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>FAIL</h1>");
        response.getWriter().println("<p>");
        cause.printStackTrace(response.getWriter());
        response.getWriter().println("<p>");
        ((Request) request).setHandled(true);
    } catch (Exception e) {
        log.error("Failed to respond with a failure.", e);
    }
}