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.github.mike10004.stormpathacctmgr.NewPasswordFormServletTest.java

@Test
public void testDoGet() throws Exception {
    System.out.println("NewPasswordFormServletTest.testDoGet");
    String emailAddress = "somebody@example.com";
    String token = "981ng9014ng4nh9014h901nh4jhqg8rejg089rjg09zahg49hqg08";
    final Application application = createNiceMock(Application.class);
    Account account = createNiceMock(Account.class);
    final RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest() {

        @Override//from   www  .java 2  s.c o  m
        public RequestDispatcher getRequestDispatcher(String path) {
            assertEquals(NewPasswordFormServlet.RESET_ENTER_NEW_PASSWORD_JSP_PATH, path);
            return requestDispatcher;
        }

    };
    mockRequest.setParameter(PasswordReset.PARAM_RESET_TOKEN, token);
    requestDispatcher.forward(mockRequest, mockResponse);
    EasyMock.expectLastCall().times(1);
    expect(account.getEmail()).andReturn(emailAddress).anyTimes();
    expect(application.verifyPasswordResetToken(token)).andReturn(account).times(1);
    replay(application, account, requestDispatcher);

    final Stormpaths stormpaths = new Stormpaths() {

        @Override
        public Application buildApplication() {
            return application;
        }

    };
    NewPasswordFormServlet instance = new NewPasswordFormServlet() {

        @Override
        protected Stormpaths createStormpaths() {
            return stormpaths;
        }

    };
    MockServletContext servletContext = new MockServletContext();
    instance.init(new MockServletConfig(servletContext));
    instance.doGet(mockRequest, mockResponse);
    String actualTargetEmailAttribute = (String) mockRequest
            .getAttribute(NewPasswordFormServlet.ATTR_TARGET_EMAIL);
    System.out.println("email attribute: " + actualTargetEmailAttribute);
    assertEquals(emailAddress, actualTargetEmailAttribute);
    System.out.println("status: " + mockResponse.getStatus());
    assertEquals(HttpServletResponse.SC_OK, mockResponse.getStatus());
}

From source file:org.obm.healthcheck.server.HealthCheckServletDefaultHandlersTest.java

@Test
public void testRootUrl() throws Exception {
    HttpResponse response = get("/");
    ImmutableMap<String, String> javaVersion = ImmutableMap.of("method", "GET", "path", "/java/version");
    ImmutableMap<String, String> javaVendor = ImmutableMap.of("method", "GET", "path", "/java/vendor");
    ImmutableMap<String, String> javaVMName = ImmutableMap.of("method", "GET", "path", "/java/vmname");
    ImmutableMap<String, String> javaEncoding = ImmutableMap.of("method", "GET", "path", "/java/encoding");

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpServletResponse.SC_OK);

    Object[] result = (Object[]) JSON.parse(IO.toString(response.getEntity().getContent()));

    assertThat(result).containsOnly(javaVendor, javaVersion, javaVMName, javaEncoding);
}

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

@Test
public void testDownloadUsingNonAuthenticatedProxy() throws Exception {
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {
        @Override//from w ww .j  av  a  2 s  .  com
        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 {
        StreamProvider df = download(dm, "mvn:x.y/z/1.0");
        assertNotNull(df);
        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:edu.duke.cabig.c3pr.utils.web.filter.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///from   w ww  .j  a va 2s .  c om
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        try {
            // Write the zipped body
            ResponseUtil.addGzipHeader(response);
            response.setContentLength(compressedBytes.length);
        } catch (ResponseHeadersNotModifiableException e) {
            return;
        }

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

From source file:org.everit.authentication.cas.ecm.tests.SampleApp.java

/**
 * Ping CAS login URL./*from  ww w .j  av  a 2s .  c o  m*/
 */
public static void pingCasLoginUrl(final BundleContext bundleContext) throws Exception {
    CloseableHttpClient httpClient = new SecureHttpClient(null, bundleContext).getHttpClient();

    HttpGet httpGet = new HttpGet(CAS_LOGIN_URL + "?" + LOCALE);
    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);
        Assert.assertEquals(CAS_PING_FAILURE_MESSAGE, HttpServletResponse.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
    } catch (Exception e) {
        LOGGER.error(CAS_PING_FAILURE_MESSAGE, e);
        Assert.fail(CAS_PING_FAILURE_MESSAGE);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consume(httpResponse.getEntity());
        }
        httpClient.close();
    }
}

From source file:com.surevine.alfresco.audit.integration.CreateDiscussionReplyTest.java

/**
 * Test sunny day scenario./* w  w  w. j  a v  a2s. com*/
 */
@Test
public void testSuccessfulCreation() {

    String requestURI = "/alfresco/s/api/forum/post/node/workspace/SpacesStore/"
            + TEST_DISCUSSION_TOPIC_NODEREF_ID + "/replies";

    mockRequest.setRequestURI(requestURI);

    try {
        JSONObject json = new JSONObject();
        json.put(AlfrescoJSONKeys.CONTENT, "<p>here is the content of the discussion topic</p>");
        json.put(AlfrescoJSONKeys.SITE, TEST_SITE);
        json.put(AlfrescoJSONKeys.PAGE, "discussions-topicview");
        json.put(AlfrescoJSONKeys.CONTAINER, "discussions");

        JSONObject item = new JSONObject();
        item.put("url", "/forum/post/node/workspace/SpacesStore/" + TEST_DISCUSSION_REPLY_NODEREF_ID);
        item.put("repliesUrl",
                "/forum/post/node/workspace/SpacesStore/" + TEST_DISCUSSION_REPLY_NODEREF_ID + "/replies");
        item.put(AlfrescoJSONKeys.NODEREF,
                StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.toString() + TEST_DISCUSSION_REPLY_NODEREF_ID);

        // Create a new JSON object for the response, which is where most of the data will come from.
        JSONObject responseJSON = new JSONObject();
        responseJSON.put("item", item);

        mockRequest.setContent(json.toString().getBytes());

        // Now put the response JSON in the response object.
        mockChain = new ResponseModifiableMockFilterChain(responseJSON.toString(), HttpServletResponse.SC_OK);

        springAuditFilterBean.doFilter(mockRequest, mockResponse, mockChain);

        Auditable audited = getSingleAuditedEvent();

        verifyGenericAuditMetadata(audited);
        assertEquals(TEST_DISCUSSION_REPLY_NODEREF_ID, audited.getSource());
        assertEquals(requestURI, audited.getUrl());
        assertEquals(TEST_SITE, audited.getSite());

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }

}

From source file:core.NiprSyncController.java

@RequestMapping(value = "/authorize", method = RequestMethod.POST)
public void authorize(@RequestBody AuthRequest request, HttpServletResponse response) {
    String s = request.getUsername() + ":" + request.getPassword();
    byte[] encodedBytes = org.apache.tomcat.util.codec.binary.Base64.encodeBase64(s.getBytes());
    String lAuthHeader = "Basic " + new String(encodedBytes);

    if (Configuration.IsAuthenticated(lAuthHeader)) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {//from  ww w .  j av a2  s  . co  m
        System.out.println("Authentication Failed");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.liferay.sync.engine.documentlibrary.handler.BaseHandler.java

@Override
public Void handleResponse(HttpResponse httpResponse) {
    try {/*  w  ww  . ja  v a 2  s.c  o  m*/
        StatusLine statusLine = httpResponse.getStatusLine();

        if (statusLine.getStatusCode() != HttpServletResponse.SC_OK) {
            _logger.error("Status code {}", statusLine.getStatusCode());

            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        doHandleResponse(httpResponse);
    } catch (Exception e) {
        handleException(e);
    }

    return null;
}

From source file:gov.nih.nci.cabig.caaers.web.filters.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///from w  w w .ja  v  a 2  s .c o  m
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        try {
            // Write the zipped body
            ResponseUtil.addGzipHeader(response);
            // see http://httpd.apache.org/docs/2.0/mod/mod_deflate.html or 'High Performance Web Sites' by Steve Souders.
            response.addHeader(VARY, "Accept-Encoding");
            response.addHeader(VARY, "User-Agent");
            response.setContentLength(compressedBytes.length);
        } catch (ResponseHeadersNotModifiableException e) {
            return;
        }

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

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

/**
 * {@inheritDoc}//  www  . ja  va2 s . 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.xml");

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

    // Prepare the request
    logger.info("Testing greeter action's xml 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.debug("Sending request to {}", request.getURI());
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = TestUtils.request(httpClient, request, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

            // 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();

            Document xml = TestUtils.parseXMLResponse(response);
            String xpath = "/greetings/greeting[@language=\"" + language + "\"]/text()";

            String greetingEncoded = new String(greeting.getBytes(charset));
            Assert.assertEquals(greetingEncoded, XPathHelper.valueOf(xml, xpath));
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}