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:de.perdoctus.synology.jdadapter.controller.JdAdapter.java

@RequestMapping(value = "/flash", method = RequestMethod.GET)
public void enableFlashButton(final HttpServletResponse resp) throws IOException {
    LOG.info("Got Request from flash click'n'load button.");
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().print("JDownloader");
}

From source file:controller.MunicipiosRestController.java

/**
 *
 * @param request//from w  w  w. jav  a 2s  .  c  o m
 * @param response
 * @return XML
 */
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
public String getXML(HttpServletRequest request, HttpServletResponse response) {
    MunicipiosDAO tabla = new MunicipiosDAO();
    XStream XML;
    List<Municipios> 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<Municipios> datos = new Datos<>();
    datos.setDatos(lista);
    XML = new XStream();
    XML.alias("municipio", Municipios.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(lista);
}

From source file:com.ns.cm.ProvisionServlet.java

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO//from   w w  w .j av  a 2 s .  c o m

    // 
    PrintWriter out = response.getWriter();
    out.println("Processed doDelete");
    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);

}

From source file:controller.IndicadoresRestController.java

/**
 *
 * @param request//  www. j  av  a  2s.  co m
 * @param response
 * @return XML
 */
@RequestMapping(method = RequestMethod.GET, produces = "application/xml")
public String getXML(HttpServletRequest request, HttpServletResponse response) {
    IndicadoresDAO tabla = new IndicadoresDAO();
    XStream XML;
    List<Indicadores> 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<Indicadores> datos = new Datos<>();
    datos.setDatos(lista);
    XML = new XStream();
    XML.alias("indicador", Indicadores.class);
    response.setStatus(HttpServletResponse.SC_OK);
    return XML.toXML(lista);
}

From source file:coria2015.server.ContentServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final URL url;
    IMAGE_URI = "/recipe/image/";
    if (request.getRequestURI().startsWith(IMAGE_URI)) {

        String recipeName = URLDecoder.decode(request.getRequestURI().substring(IMAGE_URI.length()), "UTF-8")
                .replace(" ", "-");
        String name = recipeImages.get(recipeName);
        File file = new File(imagePath, name);
        url = file.toURI().toURL();/*from   www .  j av a2 s  .c  om*/
    } else {
        url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));
    }

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}

From source file:eu.stratosphere.client.web.PactJobJSONServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");

    String jobName = req.getParameter(JOB_PARAM_NAME);
    if (jobName == null) {
        LOG.warn("Received request without job parameter name.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from   w  w  w  .  ja v a  2s. c o m*/
    }

    // check, if the jar exists
    File jarFile = new File(jobStoreDirectory, jobName);
    if (!jarFile.exists()) {
        LOG.warn("Received request for non-existing jar file.");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // create the pact plan
    PackagedProgram pactProgram;
    try {
        pactProgram = new PackagedProgram(jarFile, new String[0]);
    } catch (Throwable t) {
        LOG.info("Instantiating the PactProgram for '" + jarFile.getName() + "' failed.", t);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(t.getMessage());
        return;
    }

    String jsonPlan = null;
    String programDescription = null;

    try {
        jsonPlan = pactProgram.getPreviewPlan();
    } catch (Throwable t) {
        LOG.error("Failed to create json dump of pact program.", t);
    }

    try {
        programDescription = pactProgram.getDescription();
    } catch (Throwable t) {
        LOG.error("Failed to create description of pact program.", t);
    }

    if (jsonPlan == null && programDescription == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } else {
        resp.setStatus(HttpServletResponse.SC_OK);
        PrintWriter wrt = resp.getWriter();
        wrt.print("{ \"jobname\": \"");
        wrt.print(jobName);
        if (jsonPlan != null) {
            wrt.print("\", \"plan\": ");
            wrt.println(jsonPlan);
        }
        if (programDescription != null) {
            wrt.print(", \"description\": \"");
            wrt.print(escapeString(programDescription));
            wrt.print("\"");
        }

        wrt.println("}");
    }
}

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

@Test
public void testOneRequestSimpleFailover(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException {

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "simple";
    String url2 = baseURL2.toString() + "simple";

    try {/*w w w  .  j a v a 2s .  c om*/

        HttpResponse response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Now check on the 2nd server

        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 2,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        //and back on the 1st server
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was brough up.", 3,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

    } finally {
        HttpClientUtils.closeQuietly(client);
    }

}

From source file:com.controller.schedule.ScheduleEmailActionsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w  . j a va2 s  .c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try {
        if (!AuthenticationUtil.isUserLoggedIn(request)) {
            AuthenticationUtil.printAuthErrorToResponse(response);
            return;
        }
        Integer userId = AuthenticationUtil.getUUID(request);

        Map<String, Object> requestBodyMap = AppConstants.GSON.fromJson(new BufferedReader(request.getReader()),
                Map.class);
        if (requestBodyMap == null) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        List<String> errorMsgs = validateRequestBody(requestBodyMap);
        if (!errorMsgs.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMsgs);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        //As of now schedule description is not yet mandatory.
        String schedule_id = (String) requestBodyMap.get("schedule_id");
        String scheduleDesc = requestBodyMap.containsKey("schedule_desc")
                ? String.valueOf(requestBodyMap.get("schedule_desc"))
                : null;

        Map<String, Integer> idMap = ScheduleDAO.updatetoScheduledEmailList(userId,
                Integer.parseInt(schedule_id), requestBodyMap.get("email_subject").toString(),
                requestBodyMap.get("email_body").toString(),
                requestBodyMap.get("from_email_address").toString(),
                requestBodyMap.get("email_list").toString(), requestBodyMap.get("from_name").toString(),
                requestBodyMap.get("reply_to_email_address").toString(),
                requestBodyMap.get("to_email_addresses").toString().split(","), scheduleDesc,
                TemplateStatus.template_saved.toString());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(AppConstants.GSON.toJson(idMap));
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Invalid format for schedule time.");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (Exception ex) {
        Logger.getLogger(ScheduleEmailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:nl.dtls.fairdatapoint.api.controller.DataAccessorControllerTest.java

/**
 * Check supported accept headers./*from w  w w . j  a v  a  2s  . c o  m*/
 * 
 * @throws Exception 
 */
@Test
public void supportedAcceptHeaders() throws Exception {

    MockHttpServletRequest request;
    MockHttpServletResponse response;
    Object handler;

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    request.setMethod("GET");
    request.addHeader(HttpHeaders.ACCEPT, "text/turtle");
    request.setRequestURI("/textmining/gene-disease-association_lumc/sparql");
    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());

    request.addHeader(HttpHeaders.ACCEPT, "text/n3");
    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());

    request.addHeader(HttpHeaders.ACCEPT, "application/ld+json");
    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());

    request.addHeader(HttpHeaders.ACCEPT, "application/rdf+xml");
    handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);
    assertEquals(HttpServletResponse.SC_OK, response.getStatus());
}

From source file:com.wso2telco.premiuminfo.PremiumInfoEndpoint.java

@GET
@Path("/")
@Produces("application/json")
public Response getUserClaims(@Context HttpServletRequest request) throws OAuthSystemException {

    String response = null;/* w  w w  .  j  av a2 s  .c o  m*/
    try {
        // validate the request
        UserInfoRequestValidator requestValidator = UserInfoEndpointConfig.getInstance()
                .getUserInfoRequestValidator();
        String accessToken = requestValidator.validateRequest(request);
        // validate the access token
        UserInfoAccessTokenValidator tokenValidator = UserInfoEndpointConfig.getInstance()
                .getUserInfoAccessTokenValidator();
        OAuth2TokenValidationResponseDTO tokenResponse = tokenValidator.validateToken(accessToken);
        // build the claims
        //Validate the grant type to be implicit or authorization_code before retrieving claims
        UserInfoResponseBuilder userInfoResponseBuilder = UserInfoEndpointConfig.getInstance()
                .getUserInfoResponseBuilder();
        response = userInfoResponseBuilder.getResponseString(tokenResponse);

    } catch (UserInfoEndpointException e) {
        log.error("UserInfoEndpoint Exception occurred when calling getUserClaims : ", e);
        response = handleError(e).toString();
    } catch (OAuthSystemException e) {
        log.error("OAuthSystemException Exception occurred when calling getUserClaims : ", e);
        throw new OAuthSystemException("UserInfoEndpoint Failed");
    } catch (org.apache.oltu.oauth2.common.exception.OAuthSystemException e) {
        log.error("OAuthSystemException Exception occurred when calling getUserClaims : ", e);
    }

    ResponseBuilder respBuilder = Response.status(HttpServletResponse.SC_OK)
            .header(OAuthConstants.HTTP_RESP_HEADER_CACHE_CONTROL,
                    OAuthConstants.HTTP_RESP_HEADER_VAL_CACHE_CONTROL_NO_STORE)
            .header(OAuthConstants.HTTP_RESP_HEADER_PRAGMA,
                    OAuthConstants.HTTP_RESP_HEADER_VAL_PRAGMA_NO_CACHE);

    return respBuilder.entity(response).build();
}