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.pymegest.applicationserver.api.UsuarioController.java

@RequestMapping(value = { "/Usuario/{idsUsuarios}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsUsuarios") String idsUsuariosStr) {

    try {//from   www.jav a2  s.co m

        String[] idsUsuariosArr = idsUsuariosStr.split(",");
        List<Usuario> listaUsuarios = new ArrayList();
        for (int i = 0; i < idsUsuariosArr.length; i++) {
            listaUsuarios.add(usuarioDAO.read(Integer.parseInt(idsUsuariosArr[i])));
        }

        if (listaUsuarios.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaUsuarios);
            response.getWriter().println(json);

        }

        else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de usuarios esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.pymegest.applicationserver.api.ProductoController.java

@RequestMapping(value = { "/Producto/{idsProductos}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsProductos") String idsProductosStr) {

    try {// w w w . j a va  2 s.  c  o  m

        String[] idsProductosArr = idsProductosStr.split(",");
        List<Producto> listaProductos = new ArrayList();
        for (int i = 0; i < idsProductosArr.length; i++) {
            listaProductos.add(productoDAO.read(Integer.parseInt(idsProductosArr[i])));
        }

        if (listaProductos.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaProductos);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de productos esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.pymegest.applicationserver.api.EmpleadoController.java

@RequestMapping(value = { "/Empleado/{idsEmpleados}" }, method = RequestMethod.GET)
public void read(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("idsEmpleados") String idsEmpleadosStr) {

    try {/*from   w w w  .j  av a 2  s  .c o  m*/

        String[] idsEmpleadosArr = idsEmpleadosStr.split(",");
        List<Empleado> listaEmpleados = new ArrayList();
        for (int i = 0; i < idsEmpleadosArr.length; i++) {
            listaEmpleados.add(empleadoDAO.read(Integer.parseInt(idsEmpleadosArr[i])));
        }

        if (listaEmpleados.isEmpty() == false) {

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(listaEmpleados);
            response.getWriter().println(json);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("La lista de empleados esta vacia.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.chrischurchwell.jukeit.server.ServerHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Debug.debug("Handling Web Request: ", target);

    if (target.equalsIgnoreCase("/")) {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);//from  w ww .  j a  v  a 2  s  . c  o m

        Template template = cfg.getTemplate("index.html");

        Map<String, Object> dataRoot = new HashMap<String, Object>();
        dataRoot.put("serverName", JukeIt.getInstance().getConfig().getString("serverName"));
        dataRoot.put("allowUpload", JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads"));

        dataRoot.put("files", JukeIt.getServerFileList());

        try {
            template.process(dataRoot, response.getWriter());
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return;
    }

    if (target.equalsIgnoreCase("/robots.txt")) {
        response.setContentType("text/plain;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        response.getWriter().println("User-agent: *");
        response.getWriter().println("Disallow: /");

        return;
    }

    if (target.equalsIgnoreCase("/upload")) {

        if (!JukeIt.getInstance().getConfig().getBoolean("allowWebServerUploads")) {
            return;
        }

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);

        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().println("No File Upload Detected");
            return;
        }

        /* Straight from commons.io docs */

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {

            List<FileItem> items = castList(FileItem.class, upload.parseRequest(request));

            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    //processFormField(item);
                } else {
                    //processUploadedFile(item);
                    //String fieldName = item.getFieldName();
                    //String fileName = item.getName();
                    //String contentType = item.getContentType();
                    //boolean isInMemory = item.isInMemory();
                    //long sizeInBytes = item.getSize();

                    if (!item.getName().endsWith(".ogg") && !item.getName().endsWith(".wav")
                            && !item.getName().endsWith(".mp3")) {
                        response.getWriter().println("File must be a .ogg or .wave");
                        return;
                    }

                    String name = item.getName().replace(" ", "_");
                    File uploadedFile = new File(JukeIt.getInstance().getDataFolder(), "music/" + name);
                    item.write(uploadedFile);

                    response.getWriter().println("1");
                    return;
                }
            }

        } catch (FileUploadException e) {
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            response.getWriter().println(e.getMessage());
            return;
        }

        return;
    }

}

From source file:com.graphaware.module.resttest.RestTestApi.java

@RequestMapping(value = "/assertSameGraph", method = RequestMethod.POST)
@ResponseBody/*ww w.j a v  a2s. c  om*/
public String assertSameGraph(@RequestBody RestTestRequest request, HttpServletResponse response)
        throws IOException {
    if (request.getCypher() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cypher statement must be provided");
    }

    try {
        GraphUnit.assertSameGraph(database, request.getCypher(), resolveInclusionPolicies(request));
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (AssertionError error) {
        response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
        return error.getMessage();
    }
}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/*from w w  w. ja v a  2s .co m*/
        // Get the uri of the resource
        long jobId = getJobId(restUtils.extractRepositoryUri(req.getPathInfo()));

        // get the resources....
        Job job = reportSchedulerService.getJob(jobId);

        StringWriter sw = new StringWriter();
        // create JAXB context and instantiate marshaller

        restUtils.getMarshaller(Job.class).marshal(job, sw);

        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, sw.toString());

    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage());
    }
}

From source file:com.google.api.server.spi.handlers.CorsHandlerTest.java

@Test
public void handle_invalidMethod() {
    request.addHeader("Access-Control-Request-Method", "DEELEEETE");
    request.addHeader("Access-Control-Request-Headers", TEST_HEADER);
    request.addHeader("Origin", ORIGIN);

    handler.handle(request, response);/*w w w .  j  ava  2s .  co  m*/

    assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
    assertThat(response.getHeader("Access-Control-Allow-Origin")).isNull();
    assertThat(response.getHeader("Access-Control-Allow-Headers")).isNull();
    assertThat(response.getHeader("Access-Control-Max-Age")).isNull();
    assertThat(response.getHeader("Access-Control-Allow-Credentials")).isNull();
    assertThat(response.getHeader("Access-Control-Allow-Methods")).isNull();
}

From source file:com.fpmislata.banco.presentation.controladores.EntidadBancariaController.java

@RequestMapping(value = "/entidadbancaria", method = RequestMethod.GET, produces = "application/json")
public void find(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    try {//from w w w.  j  av a  2  s .  c o  m

        List<EntidadBancaria> entidadBancarias;

        if (httpServletRequest.getParameter("nombre") != null) {

            entidadBancarias = entidadBancariaService.findByNombre(httpServletRequest.getParameter("nombre"));
        } else {
            entidadBancarias = entidadBancariaService.findAll();
        }

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        String jsonSalida = jsonTransformer.ObjectToJson(entidadBancarias);
        httpServletResponse.getWriter().println(jsonSalida);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.nif.NIFMultiController.java

/**
 * Generates a csv file from scenarios/*from  w  w  w  .j  a v  a 2s  .  c o  m*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView getScenariosCSVFile(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Controller for creating csv file for NIF");
    OutputStream out = null;
    int headerBufferSize = 8096;

    response.setHeader("Content-Type", "text/csv");
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=EEGbase_scenarios.csv");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);

    log.debug("Generating csv");
    out = csvFactory.generateScenariosCsvFile();
    ByteArrayOutputStream bout = (ByteArrayOutputStream) out;
    response.getOutputStream().write(bout.toByteArray());
    return null;
}