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.obm.healthcheck.server.HealthCheckServletDefaultHandlersTest.java

@Test
public void testGetJavaVendor() throws Exception {
    HttpResponse response = get("/java/vendor");

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpServletResponse.SC_OK);
    assertThat(IO.toString(response.getEntity().getContent())).isEqualTo(System.getProperty("java.vendor"));
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTRole.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    WSRoleSearchCriteria criteria = restUtils.populateServiceObject(req.getPathInfo(), req.getParameterMap(),
            WSRoleSearchCriteria.class);

    WSRole[] roles = null;// w  w w  .  java2s.  co  m

    try {
        // get the resources....
        roles = userAndRoleManagementService.findRoles(criteria);
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                "could not locate roles in uri: " + criteria.getRoleName() + axisFault.getLocalizedMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug(roles.length + " roles were found");
    }

    String marshal = generateSummeryReport(roles);
    if (log.isDebugEnabled()) {
        log.debug("Marshaling OK");
    }
    restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, marshal);
}

From source file:com.cloud.servlet.StaticResourceServletTest.java

@Test
public void testNotCompressedFile() throws ServletException, IOException {
    final HttpServletResponse response = doGetTest("index.html");
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
    Mockito.verify(response).setContentType("text/html");
    Mockito.verify(response, Mockito.times(0)).setHeader("Content-Encoding", "gzip");
}

From source file:com.tc.admin.UpdateCheckRequestTest.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

    String[] expectedParams = { "kitID", "pageID", "id", "os-name", "jvm-name", "jvm-version", "platform",
            "tc-version", "tc-product", "source" };
    Map paramMap = request.getParameterMap();
    for (String expectedParam : expectedParams) {
        if (paramMap.get(expectedParam) == null) {
            response.getWriter().println("Missing parameter '" + expectedParam + "'");
            return;
        }/*from ww  w. j  a  va2 s  .com*/
    }
    if (paramMap.size() != expectedParams.length) {
        response.getWriter()
                .println("Parameter count doesn't match expected count='" + expectedParams.length + "'");
        return;
    }
    response.getWriter().println("OK");
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

@RequestMapping("/accessToken")
public HttpEntity<String> token(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {

    try {//from   w  w  w . j  av a  2 s  .co m
        // OAuth
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);

        // ??id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            return buildInvalidClientIdResponse();

        }

        // KEY?
        if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
            return buildInvalidClientSecretResponse();
        }

        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        // ??AUTHORIZATION_CODEPASSWORDREFRESH_TOKEN
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildBadAuthCodeResponse();
            }
            // TODO ??
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPassword(oauthRequest.getUsername(), oauthRequest.getPassword())) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            // https://github.com/zhouyongtao/homeinns-web
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildInvalidRefreshTokenResponse();
            }
        }

        // ?Access Token
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        final String accessToken = oauthIssuerImpl.accessToken();
        oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
        final String refreshToken = oauthIssuerImpl.refreshToken();
        oAuthService.addAccessToken(refreshToken, oAuthService.getUsernameByAuthCode(authCode));

        // ?OAuth?
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken).setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
                .setTokenType(TokenType.BEARER.toString()).setRefreshToken(refreshToken).buildJSONMessage();

        // ?OAuthResponse?ResponseEntity
        return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));

    } catch (OAuthProblemException e) {
        // ?
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return new ResponseEntity<String>(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
    }
}

From source file:org.jboss.as.test.integration.web.response.DefaultResponseCodeTestCase.java

@Test
public void testDefaultResponseCode() throws Exception {
    ModelNode operation = createOpNode("subsystem=undertow/server=default-server/host=default-host",
            "write-attribute");
    operation.get("name").set("default-response-code");
    operation.get("value").set(506);
    executeOperation(operation);/*from w  w w. jav  a  2 s  .co m*/
    operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "remove");
    operation.get("address").add("location", "/");
    executeOperation(operation);
    executeReloadAndWaitForCompletion(getModelControllerClient());
    try {
        HttpGet httpget = new HttpGet(url.toString() + URL_PATTERN);
        HttpResponse response = this.httpclient.execute(httpget);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        String badUrl = url.toString();
        badUrl = badUrl.substring(0, badUrl.length() - 1);
        httpget = new HttpGet(badUrl + "xxx/xxx");
        response = this.httpclient.execute(httpget);
        Assert.assertEquals(506, response.getStatusLine().getStatusCode());
    } finally {
        operation = createOpNode("subsystem=undertow/server=default-server/host=default-host",
                "undefine-attribute");
        operation.get("name").set("default-response-code");
        executeOperation(operation);
        operation = createOpNode("subsystem=undertow/server=default-server/host=default-host", "add");
        operation.get("address").add("location", "/");
        operation.get("handler").set("welcome-content");
        executeOperation(operation);
        executeReloadAndWaitForCompletion(getModelControllerClient());
    }
}

From source file:ee.pri.rl.blog.web.filter.BlogPageCachingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    boolean cacheEnabled = blogService.getSetting(SettingName.PAGE_CACHE_ENABLED).getBoolValue();
    boolean cacheable = cacheEnabled && !(Session.exists() && ((BlogSession) Session.get()).isAuthenticated());
    if (cacheable && request instanceof HttpServletRequest) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        try {/*  ww  w . j a va 2s.c om*/
            String key = "#PAGE" + new URI(httpServletRequest.getRequestURI()).getPath();
            Cache cache = cacheAdministrator.getCache();

            ResponseContent respContent = null;
            try {
                respContent = (ResponseContent) cache.getFromCache(key);
                log.debug("Sending cached page " + key);
                respContent.writeTo(response, false, false);
            } catch (NeedsRefreshException e) {
                log.debug("Page needs refresh");
                CacheHttpServletResponseWrapper cacheResponse = new CacheHttpServletResponseWrapper(
                        (HttpServletResponse) response, false, Long.MAX_VALUE, CacheFilter.LAST_MODIFIED_OFF,
                        CacheFilter.EXPIRES_OFF, 0);

                chain.doFilter(request, cacheResponse);
                cacheResponse.flushBuffer();

                ResponseContent content = cacheResponse.getContent();
                if (cacheResponse.getStatus() == HttpServletResponse.SC_OK) {
                    // Store only pages with status SC_OK
                    cache.putInCache(key, content, new String[] { "pageCache" }, null, null);
                    log.debug("Page " + key + " stored in cache");
                } else {
                    // Cancel update
                    cache.cancelUpdate(key);
                }
            }
        } catch (URISyntaxException e) {
            log.warn("Invalid URI: " + httpServletRequest.getRequestURI());
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }
}

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

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

    if (MEDIA_TYPE_JSON.equals(mediaType)) {
        // 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);//from  w w w.  j  av  a 2 s . com
    } else {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
    }
}

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

@Test
@OperateOnDeployment(DEPLOYMENT_1)/*from   w w w. j  a  va  2 s.c  o m*/
public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL)
        throws IOException, URISyntaxException {

    // returns the URL of the deployment (http://127.0.0.1:8180/distributable)
    URI uri = SimpleServlet.createURI(baseURL);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
            Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        response = client.execute(new HttpGet(uri));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
            // This won't be true unless we have somewhere to which to replicate
            Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:org.sonatype.nexus.plugins.rrb.MavenRepositoryReaderIT.java

@Before
public void setUp() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    reader = new MavenRepositoryReader(httpClient, queryStringBuilder);

    // Create a Jetty server with a handler that returns the content of the
    // given target (i.e. an emulated html, S3Repo, etc, file from the test
    // resources)
    Handler handler = new AbstractHandler() {

        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            String path = target;
            if (path.endsWith("/") && StringUtils.isNotEmpty(request.getParameter("prefix"))) {
                String prefix = request.getParameter("prefix");
                path = path + prefix.replaceAll("/", "-");
            } else if (target.endsWith("/")) {
                // might need welcome pages later.
                path += "root";
            }/*ww  w .  j a va  2 s.  co m*/

            response.setStatus(HttpServletResponse.SC_OK);
            InputStream stream = this.getClass().getResourceAsStream(path);

            // added to make old tests work
            // we need to fall back to the file name that matches
            if (stream == null && path.endsWith("root")) {
                path = target;
                stream = this.getClass().getResourceAsStream(path);
            }

            if (stream == null) {
                System.out.println("Error handling: " + path);
            }

            StringBuilder result = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            String line = null;
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));
            }
            response.getWriter().println(result.toString());
            ((Request) request).setHandled(true);
        }
    };

    server = new BlockingServer(0); // We choose an arbitrary server port
    server.setHandler(handler); // Assign the handler of incoming requests
    server.start();

    // After starting we must find out the host:port, so we know how to
    // connect to the server in the tests
    for (Connector connector : server.getConnectors()) {
        nameOfConnector = connector.getName();
        break; // We only need one connector name (and there should only be
        // one...)
    }
}