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.ebay.pulsar.metric.servlet.MetricRestServlet.java

private void getCounters(final HttpServletRequest request, final String pathInfo,
        final HttpServletResponse response) throws Exception {
    String queryString = request.getQueryString();
    QueryParam queryParam = getCassandraQueryParam(queryString);
    ListenableFuture<List<Counter>> future = metricService.findCounters(
            (String) queryParam.getParameters().get(QueryParam.METRIC_NAME),
            (String) queryParam.getParameters().get(QueryParam.GROUP_ID));
    try {/* www .  ja va  2  s.c o  m*/
        List<Counter> counters = future.get(5000, TimeUnit.MILLISECONDS);
        String result = counterResultWriter.writeValueAsString(counters);
        response.getWriter().print(result);
        response.setContentLength(result.length());
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (TimeoutException e) {
        response.getWriter().print(QUERY_CASSANDRA_TIMEOUT);
        response.setContentLength(QUERY_CASSANDRA_TIMEOUT.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ExecutionException e) {
        response.getWriter().print(QUERY_CASSANDRA_ERROR);
        response.setContentLength(QUERY_CASSANDRA_ERROR.length());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java

public HttpResponse logout() throws IOException {
    HttpResponse response;//from  ww  w  .  j ava2  s. c o  m
    try {
        if (urlConnection != null) {
            closeUrlConnection();
        }
    } finally {
        Request request = Request.Post(url + "/logout?client-app=STUDIO").addHeader(authorisationHeader);
        response = request.execute().returnResponse();
        if (returnStatusCode(response) != HttpServletResponse.SC_OK && authorisationHeader != null) {
            LOGGER.error(messages.getMessage("error.logoutFailed",
                    extractResponseInformationAndConsumeResponse(response)));
        }
    }
    return response;
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineImpl.java

/**
 * @param serviceName the logical service name. Will be used as a namespace for cache keys
 * @param request the REST request that provides the soruce data
 * @param responseObservable the response observable obtained by the {@link ResilientHttp}
 * @param caching the caching layer to use
 *//*from   w w  w.j av  a 2 s  . c  o  m*/
JsonPipelineImpl(String serviceName, Request request, Observable<Response> responseObservable,
        CacheAdapter caching) {

    if (isNotBlank(serviceName)) {
        this.sourceServiceNames.add(serviceName);
    }
    this.request = request;

    this.caching = caching;
    this.descriptor = isNotBlank(request.url()) ? "GET(" + request.url() + ")" : "EMPTY()";

    this.dataSource = Observable.create(subscriber -> {

        responseObservable.subscribe(new Observer<Response>() {

            @Override
            public void onNext(Response response) {
                try {
                    int statusCode = response.status();
                    log.debug("received " + statusCode + " response (" + response.reason() + ") with from "
                            + request.url());
                    if (statusCode == HttpServletResponse.SC_OK) {
                        subscriber.onNext(JacksonFunctions.stringToNode(response.body().asString()));
                    } else {
                        String msg = "Request for " + request.url() + " failed with HTTP status code: "
                                + statusCode + " (" + response.reason() + ")";
                        subscriber.onError(new JsonPipelineInputException(statusCode, msg));
                    }
                } catch (IOException ex) {
                    subscriber.onError(new JsonPipelineInputException(500,
                            "Failed to read JSON response from " + request.url(), ex));
                }
            }

            @Override
            public void onCompleted() {
                subscriber.onCompleted();
            }

            @Override
            public void onError(Throwable e) {
                /* TODO: consider to also wrap these exceptions in an JsonPipelineInputException with the following code
                int statusCode = 500;
                if (e instanceof IllegalResponseRuntimeException) {
                  statusCode = ((IllegalResponseRuntimeException)e).getResponseStatusCode();
                }
                subscriber.onError(new JsonPipelineInputException(statusCode, "An exception occured connecting to " + request.url(), e));
                 */
                subscriber.onError(e);
            }
        });

    });
}

From source file:org.magnum.mobilecloud.video.VideoSvcCtrl.java

@PreAuthorize("hasRole(USER)")
@RequestMapping(method = RequestMethod.POST, value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike")
public @ResponseBody void unlikeVideo(@PathVariable("id") long id, Principal principal,
        HttpServletResponse response) {/*from  www  .  j  a v  a  2 s  . c  o  m*/
    Video v = videoRepo.findOne(id);
    if (v != null) {
        HashSet<String> likers = v.getLikers();
        if (likers.contains(principal.getName())) {
            likers.remove(principal.getName());
            videoRepo.save(v);
            response.setStatus(HttpServletResponse.SC_OK);
        } else
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.epam.wilma.extras.shortcircuit.ShortCircuitResponseInformationFileHandler.java

/**
 * Saves the map to a folder, to preserve it for later use.
 *
 * @param httpServletResponse is the response object
 * @return with the response body - that is a json info about the result of the call
 *///from  w  w w . jav  a 2 s .  co  m
String savePreservedMessagesFromMap(String path, FileFactory fileFactory,
        FileOutputStreamFactory fileOutputStreamFactory, HttpServletResponse httpServletResponse) {
    String response = null;
    String filenamePrefix = "sc" + UniqueIdGenerator.getNextUniqueId() + "_";
    if (!SHORT_CIRCUIT_MAP.isEmpty()) {
        String[] keySet = SHORT_CIRCUIT_MAP.keySet().toArray(new String[SHORT_CIRCUIT_MAP.size()]);
        for (String entryKey : keySet) {
            ShortCircuitResponseInformation information = SHORT_CIRCUIT_MAP.get(entryKey);
            if (information != null) { //save only the cached files
                //save this into file, folder is in folder variable
                String filename = path + filenamePrefix + UniqueIdGenerator.getNextUniqueId() + ".json";
                File file = fileFactory.createFile(filename);
                try {
                    saveMapObject(fileOutputStreamFactory, file, entryKey, information);
                } catch (IOException e) {
                    String message = "Cache save failed at file: " + filename + ", with message: "
                            + e.getLocalizedMessage();
                    logger.info("ShortCircuit: " + message);
                    response = "{ \"resultsFailure\": \"" + message + "\" }";
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    break;
                }
            }
        }
    }
    if (response == null) {
        String message = "Cache saved as: " + path + filenamePrefix + "*.json files";
        response = "{ \"resultsSuccess\": \"" + message + "\" }";
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        logger.info("ShortCircuit: " + message);
    }
    return response;
}

From source file:eu.eidas.node.connector.ConnectorExceptionHandlerServlet.java

/**
 * Prepares exception redirection, or if no information is available to redirect, prepares the exception to be
 * displayed. Also, clears the current session object, if not needed.
 *
 * @return {ERROR} if there is no URL to return to, {SUCCESS} otherwise.
 *//*from  w w w . j  av a  2s .co m*/
private void handleError(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*
      Current exception.
     */
    AbstractEIDASException exception;
    /*
      URL to redirect the citizen to.
     */
    String errorRedirectUrl;

    String retVal = NodeViewNames.INTERCEPTOR_ERROR.toString();
    try {
        // Prevent cookies from being accessed through client-side script.
        setHTTPOnlyHeaderToSession(false, request, response);

        //Set the Exception
        exception = (AbstractEIDASException) request.getAttribute("javax.servlet.error.exception");
        prepareErrorMessage(exception, request);
        errorRedirectUrl = prepareSession(exception, request);
        request.setAttribute(NodeParameterNames.EXCEPTION.toString(), exception);
        retVal = NodeViewNames.ERROR.toString();

        if (!StringUtils.isBlank(exception.getSamlTokenFail()) && null != errorRedirectUrl) {
            retVal = NodeViewNames.SUBMIT_ERROR.toString();
        } else {
            LOG.debug("BUSINESS EXCEPTION - null redirectUrl or SAML response");
            retVal = NodeViewNames.INTERCEPTOR_ERROR.toString();
        }

    } catch (Exception e) {
        LOG.info("BUSINESS EXCEPTION: in exception handler: " + e, e);
    }
    //Forward to error page
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(retVal);
    response.setStatus(HttpServletResponse.SC_OK);
    dispatcher.forward(request, response);
}

From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowControllerTest.java

@Test
public void testGetWorkflowsAsArchive() throws IOException {
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletOutputStream sos = mock(ServletOutputStream.class);
    when(response.getOutputStream()).thenReturn(sos);
    List<Long> idList = new ArrayList<>();
    idList.add(0L);//from ww  w. j a va 2 s . c  o  m
    workflowController.get(1L, idList, Optional.of("zip"), response);
    verify(workflowService, times(1)).getWorkflowsAsArchive(1L, idList);
    verify(response, times(1)).setStatus(HttpServletResponse.SC_OK);
    verify(response, times(1)).setContentType("application/zip");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
    verify(response, times(1)).addHeader(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"archive.zip\"");
    verify(sos, times(1)).write(Mockito.any());
    verify(sos, times(1)).flush();
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

private void add(HttpServletRequest request, String pathInfo, HttpServletResponse response) throws Exception {
    String eventType = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);

    UTF8InputStreamReaderWrapper reader;

    if (request.getCharacterEncoding() != null) {
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream(), request.getCharacterEncoding());
    } else {/*from   www .jav  a  2 s  . c om*/
        reader = new UTF8InputStreamReaderWrapper(request.getInputStream());
    }

    Map<String, Object> values = mapper.readValue(reader, TYPE_FLATMAP);

    if (validator != null) {
        ValidationResult result = validator.validate(values, eventType);
        if (result == null || result.isSuccess()) {
            JetstreamEvent event = createEvent(values, eventType);
            inboundChannel.onMessage(event);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print(validateReusltWriter.writeValueAsString(result));
        }
    } else {
        JetstreamEvent event = createEvent(values, eventType);
        inboundChannel.onMessage(event);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

From source file:ch.entwine.weblounge.test.harness.rest.SearchEndpointTest.java

/**
 * Performs a search request for existing content.
 * /*ww w.j a  va2 s  .co m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void searchExisting(String serverUrl) throws Exception {
    logger.info("Preparing test of search rest api");

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/search");

    // Prepare the request
    logger.info("Searching for a page");
    HttpGet searchRequest = new HttpGet(requestUrl);

    // Send the request. The response should be a 400 (bad request)
    logger.debug("Sending empty get request to {}", searchRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that don't yield a result
    String searchTerms = "xyz";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, searchTerms));
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("0", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that should yield a result
    searchTerms = "Friedrich Nietzsche Suchresultat";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
    String[][] params = new String[][] { { "limit", "5" } };
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("5", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
        assertEquals("4bb19980-8f98-4873-a813-000000000006",
                XPathHelper.valueOf(xml, "/searchresult/result/id"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for exact matches on subjects
    String[] exactMatches = { "Search Topic A", "Search Topic B" };
    for (String searchTerm : exactMatches) {

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for exact match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount == 5);
            Assert.assertTrue(hitCount == 5);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

    }

    // Check for partial matches in fields that should be supporting partial
    // matches
    String[] partialSearchTerms = { "Kurzer Seitentitel", // German title
            "Il titre de la page", // French title
            "Lange Beschreibung", // German description
            "Dscription longue", // French description
            "Hans Muster", // creator, publisher
            "Amlie Poulard", // modifier
            "Friedrich Nietzsche Suchresultat", // element text
            "Ein amsanter Titel", // German element text
            "Un titre joyeux" // French element text
    };

    for (String searchTerm : partialSearchTerms) {
        int fullMatchDocumentCount = 0;
        int fullMatchHitCount = 0;

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for full match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            fullMatchDocumentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            fullMatchHitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(fullMatchDocumentCount >= 1);
            Assert.assertTrue(fullMatchHitCount >= fullMatchDocumentCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Full match lowercase
        httpClient = new DefaultHttpClient();
        String lowerCaseSearchTerm = searchTerm.toLowerCase();
        searchRequest = new HttpGet(
                UrlUtils.concat(requestUrl, URLEncoder.encode(lowerCaseSearchTerm, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for lowercase match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount >= fullMatchDocumentCount);
            Assert.assertTrue(hitCount >= fullMatchHitCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Partial match
        for (String partialSearchTerm : StringUtils.split(searchTerm)) {
            httpClient = new DefaultHttpClient();
            searchRequest = new HttpGet(
                    UrlUtils.concat(requestUrl, URLEncoder.encode(partialSearchTerm, "utf-8")));
            params = new String[][] { { "limit", "5" } };
            logger.info("Sending search request for partial match of '{}' to {}", searchTerm, requestUrl);
            try {
                HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
                Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
                Document xml = TestUtils.parseXMLResponse(response);
                int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
                int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
                Assert.assertTrue(documentCount > 0);
                Assert.assertTrue(hitCount > 0);
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

}

From source file:org.appverse.web.framework.backend.security.oauth2.resourceserver.handlers.OAuth2LogoutHandler.java

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    // We get the token and then we remove it from the tokenStore
    // We have to take into account that the OAuth2 spec allows the access token to be passed
    // in the authorization header or as a parameter
    String authorizationHeader = request.getHeader("authorization");
    String accessToken = null;/*from   ww w. ja v a 2  s . com*/

    if (authorizationHeader != null) {
        String authorizationType = authorizationHeader.substring(0, OAuth2AccessToken.BEARER_TYPE.length());
        if (authorizationType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) {

            accessToken = authorizationHeader.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
        }
    } else {
        accessToken = request.getParameter("access_token");
    }

    if (accessToken != null) {
        final OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(accessToken);

        if (oAuth2AccessToken != null) {
            tokenStore.removeAccessToken(oAuth2AccessToken);
        }
    }

    response.setStatus(HttpServletResponse.SC_OK);
}