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.streamsets.pipeline.stage.origin.restservice.RestServiceReceiver.java

@Override
public boolean process(HttpServletRequest req, InputStream is, HttpServletResponse resp) throws IOException {
    // Capping the size of the request based on configuration to avoid OOME
    is = createBoundInputStream(is);/*from   w w w.  j a  v a  2s .  c  om*/

    // Create new batch (we create it up front for metrics gathering purposes
    BatchContext batchContext = getContext().startBatch();

    List<Record> requestRecords = parseRequestPayload(req, is);

    // If HTTP Request Payload is empty, add Empty Payload Record with all HTTP Request Attributes
    if (CollectionUtils.isEmpty(requestRecords)) {
        requestRecords.add(createEmptyPayloadRecord(req));
    }

    // dispatch records to batch
    for (Record record : requestRecords) {
        batchContext.getBatchMaker().addRecord(record);
    }

    boolean returnValue = getContext().processBatch(batchContext);

    // Send response
    int responseStatusCode = HttpServletResponse.SC_OK;
    Set<Integer> statusCodesFromResponse = new HashSet<>();
    String errorMessage = null;

    List<Record> successRecords = new ArrayList<>();
    List<Record> errorRecords = new ArrayList<>();
    for (Record responseRecord : batchContext.getSourceResponseRecords()) {
        String statusCode = responseRecord.getHeader().getAttribute(STATUS_CODE_RECORD_HEADER_ATTR_NAME);
        if (statusCode != null) {
            statusCodesFromResponse.add(Integer.valueOf(statusCode));
        }
        if (responseRecord.getHeader().getErrorMessage() == null) {
            successRecords.add(responseRecord);
        } else {
            errorMessage = responseRecord.getHeader().getErrorMessage();
            errorRecords.add(responseRecord);
        }
    }

    if (statusCodesFromResponse.size() == 1) {
        responseStatusCode = statusCodesFromResponse.iterator().next();
    } else if (statusCodesFromResponse.size() > 1) {
        // If we received more than one status code, return 207 MULTI-STATUS Code
        // https://httpstatuses.com/207
        responseStatusCode = 207;
    }

    Record responseEnvelopeRecord = HttpStageUtil.createEnvelopeRecord(getContext(), getParserFactory(),
            successRecords, errorRecords, responseStatusCode, errorMessage, responseConfig.dataFormat);
    resp.setStatus(responseStatusCode);
    resp.setContentType(HttpStageUtil.getContentType(responseConfig.dataFormat));

    try (DataGenerator dataGenerator = getGeneratorFactory().getGenerator(resp.getOutputStream())) {
        dataGenerator.write(responseEnvelopeRecord);
        dataGenerator.flush();
    } catch (DataGeneratorException e) {
        throw new IOException(e);
    }

    return returnValue;
}

From source file:com.thoughtworks.go.server.controller.GoConfigAdministrationController.java

@RequestMapping(value = "/admin/restful/configuration/file/GET/historical-xml", method = RequestMethod.GET)
public void getConfigRevision(@RequestParam(value = "version", required = true) String version,
        HttpServletResponse response) throws Exception {
    GoConfigRevision configRevision = goConfigService.getConfigAtVersion(version);
    String md5 = configRevision.getMd5();
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/xml");
    response.setCharacterEncoding("utf-8");
    response.setHeader(X_CRUISE_CONFIG_MD5, md5);
    if (configRevision.isByteArrayBacked()) {
        IOUtils.write(configRevision.getConfigXmlBytes(), response.getOutputStream());
    } else {//w ww . j a  v  a2 s  .c o m
        response.getWriter().write(configRevision.getContent());
    }
}

From source file:controller.TemasNivel2RestController.java

/**
 *
 * @param request/*from   w ww.  j a  v a2 s.co  m*/
 * @param response
 * @return XML
 */
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
public String getXML(HttpServletRequest request, HttpServletResponse response) {
    TemasNivel2DAO tabla = new TemasNivel2DAO();
    XStream XML;
    List<TemasNivel2> lista;

    try {
        lista = tabla.selectAll();

        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            XML = new XStream();
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        XML = new XStream();
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }

    Datos<TemasNivel2> datos = new Datos<>();
    datos.setDatos(lista);
    XML = new XStream();
    XML.alias("tema-nivel-2", TemasNivel2.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(lista);
}

From source file:controller.TemasNivel1RestController.java

/**
 *
 * @param request/*from w w w  . j av  a  2s.  c  o  m*/
 * @param response
 * @return XML
 */
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
public String getXML(HttpServletRequest request, HttpServletResponse response) {
    TemasNivel1DAO tabla = new TemasNivel1DAO();
    XStream XML;
    List<TemasNivel1> lista;

    try {
        lista = tabla.selectAll();

        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            XML = new XStream();
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        XML = new XStream();
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }

    Datos<TemasNivel1> datos = new Datos<>();
    datos.setDatos(lista);
    XML = new XStream();
    XML.alias("Temas-Nivel-1", TemasNivel1.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(lista);
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriter.java

@Override
public void write(Object response) throws IOException {
    if (response == null) {
        write(HttpServletResponse.SC_NO_CONTENT, null, null);
    } else {//  w w  w.  ja  v  a2s .co  m
        write(HttpServletResponse.SC_OK, null, writeValueAsString(ResponseUtil.wrapCollection(response)));
    }
}

From source file:controller.TemasNivel3RestController.java

/**
 *
 * @param request//from  ww w.  j  av a  2  s. co  m
 * @param response
 * @return XML
 */
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
public String getXML(HttpServletRequest request, HttpServletResponse response) {
    TemasNivel3DAO tabla = new TemasNivel3DAO();
    XStream XML;
    List<TemasNivel3> lista;

    try {
        lista = tabla.selectAll();

        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            XML = new XStream();
            XML.alias("message", Error.class);
            return XML.toXML(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        XML = new XStream();
        XML.alias("message", Error.class);
        return XML.toXML(e);
    }

    Datos<TemasNivel3> datos = new Datos<>();
    datos.setDatos(lista);
    XML = new XStream();
    XML.alias("tema-nivel-3", TemasNivel3.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(lista);
}

From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java

/**
 * Maps POM requests simulating a Maven 2 directory structure.
 * @throws IOException//w  w  w  .  j  a v  a 2 s  .co m
 */
@GET
@Path("{groupIdPath:[a-zA-Z0-9\\-\\_]+(/[a-zA-Z0-9\\-\\_]+)*}" + "/{artifactId:[a-zA-Z0-9\\-\\_\\.]+}"
        + "/{version:\\d+(\\.\\d+)*}" + "/{artifactIdFilename:[a-zA-Z0-9\\-\\_\\.]+}"
        + "-{versionFilename:\\d+(\\.\\d+)*}" + ".{fileExtension:pom(\\.sha1)?}")
@Timed
public Response getPom(@PathParam("groupIdPath") String groupIdPath, @PathParam("artifactId") String artifactId,
        @PathParam("version") String version, @PathParam("artifactIdFilename") String artifactIdFilename,
        @PathParam("versionFilename") String versionFilename, @PathParam("fileExtension") String fileExtension)
        throws IOException {

    String groupId = mapGroupId(groupIdPath);
    if (!validateBasicParams(groupId, artifactId, version, artifactIdFilename, versionFilename)) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    ArtifactType artifactType = getArtifactType(artifactId);

    // validate that version exists
    String url = getPomValidateUrl(artifactType, version);
    log.info("Validate file: {}", url);
    HttpHead get = new HttpHead(url);
    HttpResponse response = httpClient.execute(get);
    try {
        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }

    String xml = PomBuilder.build(groupId, artifactId, version, "pom");

    if (StringUtils.equals(fileExtension, "pom")) {
        return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
    }
    if (StringUtils.equals(fileExtension, "pom.sha1")) {
        return Response.ok(DigestUtils.sha1Hex(xml)).type(MediaType.TEXT_PLAIN).build();
    }
    return Response.status(Response.Status.NOT_FOUND).build();
}

From source file:ee.ria.xroad.asyncsender.ProxyClientTest.java

/**
 * Test./*from  w ww. j a v a 2s  . co m*/
 * @throws Exception if an error occurs
 */
@Test
public void sendMessageAndExpectNoResponse() throws Exception {
    createMockServer(new AbstractHandler() {
        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            checkHeader(request);

            response.setContentType(MimeTypes.TEXT_PLAIN);
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    });

    client.send(MimeTypes.TEXT_XML, getSimpleMessage());
}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String res = restUtils.extractRepositoryUri(req.getPathInfo());
    try {/*from w w  w  . j a  v a  2 s  . c  om*/
        List<ObjectPermission> permissions = permissionsService.getPermissions(res);
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, generatePermissionUsingJaxb(permissions));
    } catch (RemoteException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                e.getClass().getName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
    }
}

From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java

@Test
public void testGet() throws IOException {
    Payload payload = new Payload(HttpServletResponse.SC_OK, "some content\none two three\n\nfour");
    payload.getResponseHeaders().put("foo", "bar");
    TestServlet.setResponsePayload(payload);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/test");
    request.setQueryString("a=b");
    request.setParameter("a", new String[] { "b" });
    request.addHeader("c", "d ef");
    MockHttpServletResponse response = new MockHttpServletResponse();
    protocol.forward(request, response);

    assertRequestIsExpected(request, TestServlet.getLastRequest());
    assertResponseIsExpected(payload, response);
}