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.dasein.cloud.azure.tests.compute.AzureAffinityGroupSupportTests.java

@Test
public void deleteShouldDeleteWithCorrectRequest() throws InternalException, CloudException {

    final CloseableHttpResponse responseMock = getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK),
            null, new Header[] {});

    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 1)//from w  w w  . j av  a  2 s  .  com
        public CloseableHttpResponse execute(HttpUriRequest request) {
            assertDelete(request,
                    String.format(RESOURCE_AFFINITYGROUP, ENDPOINT, ACCOUNT_NO, AFFINITY_GROUP_ID));
            return responseMock;
        }
    };

    new AzureAffinityGroupSupport(azureMock).delete(AFFINITY_GROUP_ID);
}

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

@ApiOperation(value = "Gets a workflow's metadata by IDs", notes = "Returns metadata associated to the latest revision of the workflow.")
@ApiResponses(value = @ApiResponse(code = 404, message = "Bucket or workflow not found"))
@RequestMapping(value = "/buckets/{bucketId}/workflows/{idList}", method = GET)
public ResponseEntity<?> get(@PathVariable Long bucketId, @PathVariable List<Long> idList,
        @ApiParam(value = "Force response to return workflow XML content when set to 'xml'. Or extract workflows as ZIP when set to 'zip'.") @RequestParam(required = false) Optional<String> alt,
        HttpServletResponse response) throws MalformedURLException {
    if (alt.isPresent() && ZIP_EXTENSION.equals(alt.get())) {
        byte[] zip = workflowService.getWorkflowsAsArchive(bucketId, idList);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"archive.zip\"");
        response.addHeader(HttpHeaders.CONTENT_ENCODING, "binary");
        try {/*www .  ja v  a2  s.c o m*/
            response.getOutputStream().write(zip);
            response.getOutputStream().flush();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        return ResponseEntity.ok().build();
    } else {
        if (idList.size() == 1) {
            return workflowService.getWorkflowMetadata(bucketId, idList.get(0), alt);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
}

From source file:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho/*ww  w.ja v a  2 s.com*/
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}

From source file:io.lavagna.web.security.login.PersonaLogin.java

@Override
public boolean handleLogout(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    if ("POST".equalsIgnoreCase(req.getMethod())) {
        UserSession.invalidate(req, resp, userRepository);
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json");
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("redirectToSelf", new JsonPrimitive(true));
        resp.getWriter().write(jsonObject.toString());
    } else {/*from w  w  w .j  a va  2s .  co m*/
        req.getRequestDispatcher(logoutPage).forward(req, resp);
    }
    return true;
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2Ping.java

/**
 * Returns the OpenURLResponse of a JSON object defining image status. Status Codes:
 *//*from  w ww  . j  av  a 2  s.  co  m*/
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {
    final String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_NOT_FOUND;
    byte[] bytes = new byte[] {};

    try {
        final String id = ((URI) contextObject.getReferent().getDescriptors()[0]).toASCIIString();
        status = ReferentManager.getResolver().getStatus(id);

        if (status != HttpServletResponse.SC_NOT_FOUND) {
            final ObjectMapper mapper = new ObjectMapper();
            final ObjectNode rootNode = mapper.createObjectNode();

            String res_status = null;

            if (status == HttpServletResponse.SC_OK) {
                res_status = STATUS_OK;
            } else if (status == HttpServletResponse.SC_ACCEPTED) {
                res_status = STATUS_ACCEPTED;
            }

            rootNode.put("identifier", id);
            rootNode.put("status", res_status);
            bytes = mapper.writeValueAsBytes(rootNode);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", Integer.toString(bytes.length));
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, bytes, header_map);
}

From source file:com.wso2telco.workflow.api.WorkflowHistoryAPI.java

@GET
@Path("/operators")
@Produces(MediaType.APPLICATION_JSON)/*from w  w w.j a v a 2s. c o  m*/
public Response getAllOperators() {

    String jsonPayload;
    try {
        List<String> operators = SbHostObjectUtils.getAllOperators();
        jsonPayload = new Gson().toJson(operators);
    } catch (Exception e) {
        log.error(e);
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
    return Response.status(HttpServletResponse.SC_OK).entity(jsonPayload).build();
}

From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java

public void handleClassicRequest(final String jk, final String crypted, final HttpServletResponse resp)
        throws IOException {
    LOG.debug("Configuration: " + drClient.toString());

    try {/*from w  w w .  j av  a 2s.  c  om*/
        final String key = extractKey(jk);
        final List<URI> targets = Decrypter.decryptDownloadUri(crypted, key);
        final List<URI> fixedTargets = fixURIs(targets);

        LOG.debug("Sending download URLs to Synology NAS. Number of URIs: " + targets.size());
        for (URI target : fixedTargets) {
            drClient.addDownloadUrl(target);
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        analyticsTracker.trackEvent(ANALYTICS_EVENT_CATEGORY, "Classic Request", "added targets",
                targets.size());

    } catch (ScriptException ex) {
        LOG.error(ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to evaluate script:\n" + ex.getMessage());

    } catch (SynoException ex) {
        LOG.error(ex.getMessage(), ex);
        if (ex instanceof LoginException) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        } else {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        }

    } catch (URISyntaxException ex) {
        LOG.error("Decrypted URL seems to be corrupt.", ex);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:controller.MunicipiosRestController.java

/**
*
* @param id/*from  w w  w .  j  a  v  a2 s .  c om*/
* @param request
* @param response
* @return JSON
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
public String getByIdJSON(@PathVariable("id") int id, HttpServletRequest request,
        HttpServletResponse response) {

    MunicipiosDAO tabla = new MunicipiosDAO();
    Gson JSON;
    Municipios elemento;
    try {
        elemento = tabla.selectById(id);
        if (elemento == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existe el elemeto solicitado con id:" + id);
            JSON = new Gson();
            return JSON.toJson(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServerError", ex.getMessage());
        JSON = new Gson();
        return JSON.toJson(e);
    }

    JSON = new Gson();
    response.setStatus(HttpServletResponse.SC_OK);
    return JSON.toJson(elemento);
}

From source file:com.streamsets.pipeline.lib.http.HttpReceiverServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (validateAppId(req, res)) {
        LOG.debug("Validation from '{}', OK", req.getRemoteAddr());
        res.setHeader(HttpConstants.X_SDC_PING_HEADER, HttpConstants.X_SDC_PING_VALUE);
        res.setStatus(HttpServletResponse.SC_OK);
    }/* w ww . j av a  2  s  . co  m*/
}

From source file:com.proofpoint.http.server.TestHttpServerProvider.java

@Test
public void testHttps() throws Exception {
    config.setHttpEnabled(false).setHttpsEnabled(true).setHttpsPort(0)
            .setKeystorePath(getResource("localhost.keystore").toString()).setKeystorePassword("changeit");
    httpServerInfo = new HttpServerInfo(config, nodeInfo);

    createServer();/*w w  w.  j  a v a 2  s.  c  om*/
    server.start();

    HttpClient client = new ApacheHttpClient();
    StatusResponse response = client.execute(prepareGet().setUri(httpServerInfo.getHttpsUri()).build(),
            createStatusResponseHandler());

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