List of usage examples for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR
HttpStatus INTERNAL_SERVER_ERROR
To view the source code for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR.
Click Source Link
From source file:net.paulgray.mocklti2.tools.LtiToolController.java
@RequestMapping(value = "/api/tools/{toolId}/launch", method = RequestMethod.GET) public ResponseEntity getToolLaunchForId(@PathVariable("toolId") Integer toolId) { LtiTool tool = ltiToolService.getToolForId(toolId); List<LtiToolProxy> tools = tool.getToolProxies(); if (tools.size() > 0) { Map<String, String> params = new HashMap<>(); params.put("user_id", "mockconsumeradmin"); params.put("lis_person_name_full", "Mock Consumer Admin"); //These are required for Campus Pack: params.put("lti_message_type", "basic-lti-launch-request"); params.put("lti_version", "LTI-1p0"); params.put("resource_link_id", "1"); params.put("tool_consumer_instance_guid", "mock_lti2_consumer"); params.put("roles", "administrator"); LtiToolProxy proxy = tools.get(tools.size() - 1); String url = proxy.getSecureUrl(); String secret = proxy.getSecret(); String key = proxy.getKey(); String method = "POST"; Map<String, String> signedParameters = null; try {/*from w w w .j a v a 2 s . c o m*/ signedParameters = ltiSigner.signParameters(params, key, secret, url, method); } catch (LtiSigningException e) { e.printStackTrace(); return new ResponseEntity("LtiSigningException occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } return new ResponseEntity(new LtiLaunchRequest(signedParameters, url, method), HttpStatus.OK); } else { return new ResponseEntity(HttpStatus.NOT_FOUND); } }
From source file:org.bremersee.common.spring.autoconfigure.WebMvcExceptionResolver.java
int determineStatusCode(Exception ex) { if (ex == null) { return HttpStatus.OK.value(); } else if (ex instanceof StatusCodeAwareException) { return ((StatusCodeAwareException) ex).getHttpStatusCode(); } else if (ex instanceof IllegalArgumentException) { return HttpStatus.BAD_REQUEST.value(); } else if (instanceOf(ex.getClass(), "org.springframework.security.access.AccessDeniedException")) { return HttpStatus.FORBIDDEN.value(); } else if (instanceOf(ex.getClass(), "javax.persistence.EntityNotFoundException")) { return HttpStatus.NOT_FOUND.value(); } else {//from w ww. j av a2s . c o m return HttpStatus.INTERNAL_SERVER_ERROR.value(); } }
From source file:gateway.test.ServiceTests.java
/** * Test PUT /service/{serviceId}/*from w w w. j a v a 2s .c o m*/ */ @Test public void testUpdateMetadata() { // Mock HttpEntity<Service> request = new HttpEntity<Service>(null, null); doReturn(new ResponseEntity<PiazzaResponse>(new SuccessResponse("Yes", "Gateway"), HttpStatus.OK)) .when(restTemplate).exchange(any(String.class), eq(HttpMethod.PUT), any(request.getClass()), eq(SuccessResponse.class)); // Test ResponseEntity<PiazzaResponse> entity = serviceController.updateService("123456", mockService, user); // Verify assertTrue(entity.getBody() instanceof SuccessResponse); // Test Exception doThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).when(restTemplate).exchange( any(String.class), eq(HttpMethod.PUT), any(request.getClass()), eq(SuccessResponse.class)); ResponseEntity<PiazzaResponse> entity2 = serviceController.updateService("123456", mockService, user); assertTrue(entity2.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)); assertTrue(entity2.getBody() instanceof ErrorResponse); }
From source file:org.cloudfoundry.identity.uaa.oauth.approval.ApprovalsAdminEndpoints.java
@ExceptionHandler public View handleException(Exception t) { UaaException e = t instanceof UaaException ? (UaaException) t : new UaaException("Unexpected error", "Error accessing user's approvals", HttpStatus.INTERNAL_SERVER_ERROR.value()); Class<?> clazz = t.getClass(); for (Class<?> key : statuses.keySet()) { if (key.isAssignableFrom(clazz)) { e = new UaaException(t.getMessage(), "Error accessing user's approvals", statuses.get(key).value()); break; }/*from w w w . ja v a 2s . c o m*/ } return new ConvertingExceptionView(new ResponseEntity<ExceptionReport>(new ExceptionReport(e, false), HttpStatus.valueOf(e.getHttpStatus())), messageConverters); }
From source file:org.venice.piazza.servicecontroller.controller.ServiceController.java
/** * Gets service metadata, based on its Id. * //w w w.j ava2 s .com * @param serviceId * The Id of the service. * @return The service metadata or appropriate error */ @RequestMapping(value = "/service/{serviceId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PiazzaResponse> getServiceInfo(@PathVariable(value = "serviceId") String serviceId) { try { // Check if Service exists try { return new ResponseEntity<PiazzaResponse>(new ServiceResponse(accessor.getServiceById(serviceId)), HttpStatus.OK); } catch (ResourceAccessException rae) { LOGGER.error("Service not found", rae); return new ResponseEntity<PiazzaResponse>( new ErrorResponse(String.format("Service not found: %s", serviceId), "Service Controller"), HttpStatus.NOT_FOUND); } } catch (Exception exception) { LOGGER.error("Could not look up Service", exception); logger.log(exception.toString(), Severity.ERROR); logger.log(String.format("Could not look up Service %s", exception.getMessage()), Severity.ERROR, new AuditElement("serviceController", "gettingServiceMetadata", "Service")); return new ResponseEntity<PiazzaResponse>( new ErrorResponse(String.format("Could not look up Service %s information: %s", serviceId, exception.getMessage()), "Service Controller"), HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:gateway.test.AlertTriggerTests.java
/** * Test POST /alert/query//w ww . ja va 2 s . c o m */ @Test public void testQueryAlerts() { // Mock Alert alert = new Alert(); alert.alertId = "123456"; AlertListResponse mockResponse = new AlertListResponse(); mockResponse.data = new ArrayList<Alert>(); mockResponse.getData().add(alert); mockResponse.pagination = new Pagination(1, 0, 10, "test", "asc"); when(restTemplate.postForObject(anyString(), any(), eq(AlertListResponse.class))).thenReturn(mockResponse); // Test ResponseEntity<PiazzaResponse> entity = alertTriggerController.searchAlerts(null, 0, 10, null, null, false, user); AlertListResponse response = (AlertListResponse) entity.getBody(); // Verify assertTrue(entity.getStatusCode().equals(HttpStatus.OK)); assertTrue(response.getData().get(0).alertId.equalsIgnoreCase(alert.alertId)); assertTrue(response.getPagination().getCount().equals(1)); // Test an Exception when(restTemplate.postForObject(anyString(), any(), eq(AlertListResponse.class))) .thenThrow(new RestClientException("")); entity = alertTriggerController.searchAlerts(null, 0, 10, null, null, false, user); assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)); assertTrue(entity.getBody() instanceof ErrorResponse); }
From source file:org.mitre.uma.web.PolicyAPI.java
/** * Create a new policy on the given resource set * @param rsid//from w ww .j a v a 2s .c om * @param m * @param auth * @return */ @RequestMapping(value = "/{rsid}" + POLICYURL, method = RequestMethod.POST, produces = MimeTypeUtils.APPLICATION_JSON_VALUE) public String createNewPolicyForResourceSet(@PathVariable(value = "rsid") Long rsid, @RequestBody String jsonString, Model m, Authentication auth) { ResourceSet rs = resourceSetService.getById(rsid); if (rs == null) { m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (!rs.getOwner().equals(auth.getName())) { logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got " + auth.getName()); // authenticated user didn't match the owner of the resource set m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } Policy p = gson.fromJson(jsonString, Policy.class); if (p.getId() != null) { logger.warn("Tried to add a policy with a non-null ID: " + p.getId()); m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } for (Claim claim : p.getClaimsRequired()) { if (claim.getId() != null) { logger.warn("Tried to add a policy with a non-null claim ID: " + claim.getId()); m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } } rs.getPolicies().add(p); ResourceSet saved = resourceSetService.update(rs, rs); // find the new policy object Collection<Policy> newPolicies = Sets.difference(new HashSet<>(saved.getPolicies()), new HashSet<>(rs.getPolicies())); if (newPolicies.size() == 1) { Policy newPolicy = newPolicies.iterator().next(); m.addAttribute(JsonEntityView.ENTITY, newPolicy); return JsonEntityView.VIEWNAME; } else { logger.warn("Unexpected result trying to add a new policy object: " + newPolicies); m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR); return HttpCodeView.VIEWNAME; } }
From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java
/** * Returns all events, that are taking place on a specified date. The date parameter needs to be formatted according to the following pattern: YYYY/MM/DD. This function is invoked by GETting the URI /api/admin/event/date * @param date The selected date, correctly formatted (YYYY/MM/DD) * @return An HTTP response with a status code. If the function succeeds, a list of events is returned, otherwise an error code is returned. *///www . j a v a 2s. c o m @RequestMapping(value = "date", produces = "application/json", method = RequestMethod.GET) public ResponseEntity<List<Event>> getEventsOfDate(@RequestParam String date, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Getting events of date " + date); LocalDateTime startOfDay, endOfDay, startOfMonth, endOfMonth; ArrayList<Event> eventsOfDay = new ArrayList<>(); try { // Get start of day and start of next day startOfDay = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay(); endOfDay = startOfDay.plusDays(1); startOfMonth = LocalDate.of(startOfDay.getYear(), startOfDay.getMonth(), 1).atStartOfDay(); endOfMonth = startOfMonth.plusMonths(1); logger.debug("[" + currentUser + "] Converted to date object: " + startOfDay.toString()); } catch (DateTimeParseException e) { logger.warn("[" + currentUser + "] Unable to parse date: " + date + ": " + e.toString()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } logger.debug("Getting all single day events..."); eventsOfDay.addAll(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfDay, endOfDay, false)); logger.debug("All single day events retrieved, got " + eventsOfDay.size() + " events so far"); logger.debug("Getting all multi day events..."); //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected) eventsOfDay.addAll(Stream.concat( eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream(), //All multi date events starting within the month eventRepository.findAllByEndDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream()) //All multi date events ending within the month .distinct() //Removing all duplicated events .parallel() .filter(event -> event.getStartDate().isEqual(startOfDay.toLocalDate()) || event.getEndDate().isEqual(startOfDay.toLocalDate()) || (event.getEndDate().isAfter(endOfDay.toLocalDate()) && event.getStartDate().isBefore(startOfDay.toLocalDate()))) //Filter all multi date events that do not span over the date .collect(Collectors.toList())); logger.debug("All multi day events gathered, got " + eventsOfDay.size() + " events so far"); if (eventsOfDay.isEmpty()) { logger.warn("[" + currentUser + "] The events list of " + date + " is empty"); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } else { eventsOfDay.replaceAll(Event::getSendingObjectOnlyNameTimeId); logger.debug("[" + currentUser + "] Returning " + eventsOfDay.size() + " events for " + date); return new ResponseEntity<>(eventsOfDay, HttpStatus.OK); } }
From source file:com.sms.server.controller.AdminController.java
@RequestMapping(value = "/media/folder", method = RequestMethod.POST, headers = { "Content-type=application/json" }) @ResponseBody// ww w . j a v a 2s . co m public ResponseEntity<String> createMediaFolder(@RequestBody MediaFolder mediaFolder) { // Check mandatory fields. if (mediaFolder.getName() == null || mediaFolder.getType() == null || mediaFolder.getPath() == null) { return new ResponseEntity<>("Missing required parameter.", HttpStatus.BAD_REQUEST); } // Check unique fields if (settingsDao.getMediaFolderByPath(mediaFolder.getPath()) != null) { return new ResponseEntity<>("Media folder path already exists.", HttpStatus.NOT_ACCEPTABLE); } // Check path is readable if (!new File(mediaFolder.getPath()).isDirectory()) { return new ResponseEntity<>("Media folder path does not exist or is not readable.", HttpStatus.FAILED_DEPENDENCY); } // Add Media Folder to the database. if (!settingsDao.createMediaFolder(mediaFolder)) { LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME, "Error adding media folder with path '" + mediaFolder.getPath() + "' to database.", null); return new ResponseEntity<>("Error adding media folder to database.", HttpStatus.INTERNAL_SERVER_ERROR); } LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME, "Media folder with path '" + mediaFolder.getPath() + "' added successfully.", null); return new ResponseEntity<>("Media Folder added successfully.", HttpStatus.CREATED); }
From source file:gateway.test.DeploymentTests.java
/** * Test DELETE /deployment/{deploymentId} *//*from w ww .ja v a2s .c o m*/ @Test public void testDeleteDeployment() { // Mock the Response when(restTemplate.exchange(anyString(), any(), any(), eq(SuccessResponse.class))).thenReturn( new ResponseEntity<SuccessResponse>(new SuccessResponse("Deleted", "Access"), HttpStatus.OK)); // Test ResponseEntity<PiazzaResponse> entity = deploymentController.deleteDeployment("123456", user); // Verify assertTrue(entity.getBody() instanceof SuccessResponse); // Test an Exception when(restTemplate.exchange(anyString(), any(), any(), eq(SuccessResponse.class))) .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); entity = deploymentController.deleteDeployment("123456", user); PiazzaResponse response = entity.getBody(); assertTrue(response instanceof ErrorResponse); assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)); }