List of usage examples for javax.servlet.http HttpServletResponse SC_OK
int SC_OK
To view the source code for javax.servlet.http HttpServletResponse SC_OK.
Click Source Link
From source file:controller.IndicadoresMontoRestController.java
/** * * @param idi// w w w.j av a2s . com * @param idm * @param request * @param response * @return JSON * Este metodo se encarga de generar la lista de entidades */ @RequestMapping(value = "/{idi}/municipios/{idm}", method = RequestMethod.GET, produces = "application/json") public String getJSON(@PathVariable("idi") String idi, @PathVariable("idm") int idm, HttpServletRequest request, HttpServletResponse response) { Gson JSON; List<DatosRegistrosIdMunicipio> listaFinal; List<Registros> listaRegistros; RegistrosDAO tablaRegistros; tablaRegistros = new RegistrosDAO(); /* *obtenemos la lista Registros */ try { listaRegistros = tablaRegistros.selectAllResgistrosByIdIndicadorAndMunicipio(idi, idm); if (listaRegistros.isEmpty()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); Error e = new Error(); e.setTypeAndDescription("Warning", "No existen registros del indicador:" + idi + " asociados al municipio con id:" + idm); JSON = new Gson(); return JSON.toJson(e); } } catch (HibernateException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Error e = new Error(); e.setTypeAndDescription("errorServer", ex.getMessage()); JSON = new Gson(); return JSON.toJson(e); } listaFinal = new ArrayList<>(); for (Registros r : listaRegistros) { listaFinal.add(new DatosRegistrosIdMunicipio(r.getIdRegistros(), r.getAnio(), r.getCantidad())); } Datos<DatosRegistrosIdMunicipio> datos = new Datos<>(); datos.setDatos(listaFinal); JSON = new Gson(); response.setStatus(HttpServletResponse.SC_OK); return JSON.toJson(datos); }
From source file:org.clothocad.phagebook.controllers.LabController.java
@RequestMapping(value = "/addPIToLab", method = RequestMethod.POST) protected void addPIToLab(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { //at most we'd add like 10 PIs to a lab... Object pLabId = params.get("lab"); String labId = pLabId != null ? (String) pLabId : ""; Object pUserId = params.get("userId"); String userId = pUserId != null ? (String) pUserId : ""; boolean isValid = false; if (!labId.equals("") && !userId.equals("")) { isValid = true;/* w w w .j av a 2s.c o m*/ } if (isValid) { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); // able to query now. Lab lab = ClothoAdapter.getLab(labId, clothoObject); //Lab //Person person = ClothoAdapter.getPerson(userId, clothoObject); //if we ever wanted to use more props check priviledge maybe? List<String> labPIList = lab.getLeadPIs(); // to change JSONObject responseJSON = new JSONObject(); if (!labPIList.contains(pLabId)) { labPIList.add(userId); responseJSON.put("message", "new PI added!"); } else { responseJSON.put("message", "Person is already a PI!"); } lab.setLeadPIs(labPIList); ClothoAdapter.setLab(lab, clothoObject); response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); conn.closeConnection(); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); } else { response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); JSONObject responseJSON = new JSONObject(); responseJSON.put("message", "Lab or User Id cannot be blank."); PrintWriter out = response.getWriter(); out.print(responseJSON); out.flush(); } }
From source file:org.obm.healthcheck.server.HealthCheckServletOneHandlerTest.java
@Test public void testGetString() throws Exception { HttpResponse response = get("/testing/string"); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); assertThat(IO.toString(response.getEntity().getContent())).isEqualTo("Testing"); }
From source file:org.opencastproject.workspace.impl.WorkspaceImplTest.java
@Test public void testLongFilenames() throws Exception { WorkingFileRepository repo = EasyMock.createNiceMock(WorkingFileRepository.class); EasyMock.expect(repo.getBaseUri()).andReturn(new URI("http://localhost:8080/files")).anyTimes(); EasyMock.replay(repo);//from w w w . j a v a2 s .co m workspace.setRepository(repo); File source = new File( "target/test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/../test-classes/opencast_header.gif"); URL urlToSource = source.toURI().toURL(); TrustedHttpClient httpClient = EasyMock.createNiceMock(TrustedHttpClient.class); HttpEntity entity = EasyMock.createNiceMock(HttpEntity.class); EasyMock.expect(entity.getContent()).andReturn(new FileInputStream(source)); StatusLine statusLine = EasyMock.createNiceMock(StatusLine.class); EasyMock.expect(statusLine.getStatusCode()).andReturn(HttpServletResponse.SC_OK); HttpResponse response = EasyMock.createNiceMock(HttpResponse.class); EasyMock.expect(response.getEntity()).andReturn(entity); EasyMock.expect(response.getStatusLine()).andReturn(statusLine).anyTimes(); EasyMock.replay(response, entity, statusLine); EasyMock.expect(httpClient.execute((HttpUriRequest) EasyMock.anyObject())).andReturn(response); EasyMock.replay(httpClient); workspace.trustedHttpClient = httpClient; Assert.assertTrue(urlToSource.toString().length() > 255); try { Assert.assertNotNull(workspace.get(urlToSource.toURI())); } catch (NotFoundException e) { // This happens on some machines, so we catch and handle it. } }
From source file:eu.stratosphere.nephele.jobmanager.web.JobmanagerInfoServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("application/json"); try {/*from w ww . j a va 2 s . c om*/ if ("archive".equals(req.getParameter("get"))) { writeJsonForArchive(resp.getWriter(), jobmanager.getOldJobs()); } else if ("job".equals(req.getParameter("get"))) { String jobId = req.getParameter("job"); writeJsonForArchivedJob(resp.getWriter(), jobmanager.getArchive().getJob(JobID.fromHexString(jobId))); } else if ("groupvertex".equals(req.getParameter("get"))) { String jobId = req.getParameter("job"); String groupvertexId = req.getParameter("groupvertex"); writeJsonForArchivedJobGroupvertex(resp.getWriter(), jobmanager.getArchive().getJob(JobID.fromHexString(jobId)), ManagementGroupVertexID.fromHexString(groupvertexId)); } else if ("taskmanagers".equals(req.getParameter("get"))) { resp.getWriter().write("{\"taskmanagers\": " + jobmanager.getNumberOfTaskTrackers() + "}"); } else if ("cancel".equals(req.getParameter("get"))) { String jobId = req.getParameter("job"); jobmanager.cancelJob(JobID.fromHexString(jobId)); } else if ("updates".equals(req.getParameter("get"))) { String jobId = req.getParameter("job"); writeJsonUpdatesForJob(resp.getWriter(), JobID.fromHexString(jobId)); } else { writeJsonForJobs(resp.getWriter(), jobmanager.getRecentJobs()); } } catch (Exception e) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().print(e.getMessage()); if (LOG.isWarnEnabled()) { LOG.warn(StringUtils.stringifyException(e)); } } }
From source file:org.talend.components.dataprep.connection.DataPrepConnectionHandler.java
public HttpResponse connect() throws IOException { String encoding = "UTF-8"; if ((url == null) || (login == null) || (pass == null)) { throw new IOException( messages.getMessage("error.loginFailed", "please set the url, email and password")); }// ww w . j a v a 2 s. c om Request request = Request.Post(url + "/login?username=" + URLEncoder.encode(login, encoding) + "&password=" + URLEncoder.encode(pass, encoding) + "&client-app=studio"); HttpResponse response = request.execute().returnResponse(); authorisationHeader = response.getFirstHeader("Authorization"); if (returnStatusCode(response) != HttpServletResponse.SC_OK && authorisationHeader == null) { String moreInformation = extractResponseInformationAndConsumeResponse(response); LOGGER.error(messages.getMessage("error.loginFailed", moreInformation)); throw new IOException(messages.getMessage("error.loginFailed", moreInformation)); } return response; }
From source file:de.iew.raspimotion.controllers.MotionJpegController.java
@RequestMapping(value = "stream/{imagename:.+}") public void streamAction(HttpServletResponse response, @PathVariable String imagename) throws Exception { Assert.isTrue(validateImagename(imagename)); OutputStream out = response.getOutputStream(); try {/*w w w. j a v a2 s . c o m*/ FileDescriptor file = this.fileDao.getFileLastCreated(imagename); if (file == null) { throw new NoSuchElementException("Image was not found"); } sendCachingHeaders(response); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("multipart/x-mixed-replace;boundary=BOUNDARY"); writeFrameBoundary(out); writeFrame(out, file); long processingTime; long startTs; double fpsTime = 1000 / this.fps; long sleepTime; while (true) { startTs = System.currentTimeMillis(); file = this.fileDao.getFileLastCreated(imagename); writeFrame(out, file); processingTime = System.currentTimeMillis() - startTs; if (log.isDebugEnabled()) { log.debug("Zeitdauer fr gesamten Vorgang: " + processingTime); } sleepTime = (long) (fpsTime - processingTime); if (log.isDebugEnabled()) { log.debug("Schlafe " + sleepTime); } if (sleepTime > 0) { Thread.sleep(sleepTime); } } } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Motion JPEG handling aborted", e); } try { out.flush(); out.close(); } catch (Exception ex) { if (log.isDebugEnabled()) { log.debug("Closing failed", ex); } } } }
From source file:org.jahia.modules.portal.widgets.action.DocTreeAction.java
@Override public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource, JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { String path = ""; if (parameters.containsKey("path")) { path = parameters.get("path").get(0); return new ActionResult(HttpServletResponse.SC_OK, null, buildTree(session.getNode(path), true)); } else {// www. ja va 2 s. com return new ActionResult(HttpServletResponse.SC_OK, null, buildRoot(session)); } }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
@Override public void get(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { try {/* www. j a va 2 s.co m*/ String locationId = (path.length > 1 ? path[1] : null); if (locationId != null) { Location location = Location.getLocation(locationId); if (location == null) { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT, "The location " + locationId + " does not exist."); } resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONObject(toJSON(location))).toString()); resp.getWriter().flush(); } else { Collection<Location> locations; if (userId == null) { String apiKey = (String) headers.get(RestApi.API_KEY); Location location = null; if (apiKey != null) { ControllerRelay relay = ControllerRelay.getRelay(apiKey); if (relay != null) { location = relay.getLocation(); } } if (location == null) { locations = Collections.emptyList(); } else { locations = Collections.singletonList(location); } } else { User user = User.getUserByUserId(userId); if (user == null) { locations = Collections.emptyList(); } else { locations = user.getLocations(); } } ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (Location l : locations) { list.add(toJSON(l)); } resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONArray(list)).toString()); resp.getWriter().flush(); } } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:hudson.model.UpdateSiteTest.java
/** * Startup a web server to access resources via HTTP. * @throws Exception //from www.j a va 2s.co m */ @Before public void setUpWebServer() throws Exception { server = new Server(); SocketConnector connector = new SocketConnector(); server.addConnector(connector); server.setHandler(new AbstractHandler() { public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { if (target.startsWith(RELATIVE_BASE)) { target = target.substring(RELATIVE_BASE.length()); } String responseBody = getResource(target); if (responseBody != null) { HttpConnection.getCurrentConnection().getRequest().setHandled(true); response.setContentType("text/plain; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().write(responseBody.getBytes()); } } }); server.start(); baseUrl = new URL("http", "localhost", connector.getLocalPort(), RELATIVE_BASE); }