Example usage for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR

List of usage examples for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR.

Prototype

HttpStatus INTERNAL_SERVER_ERROR

To view the source code for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR.

Click Source Link

Document

500 Internal Server Error .

Usage

From source file:de.pentasys.playground.springbootexample.SampleActuatorApplicationTests.java

@Test
public void testHtmlErrorPage() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
    HttpEntity<?> request = new HttpEntity<Void>(headers);
    ResponseEntity<String> entity = new TestRestTemplate("admin", getPassword())
            .exchange("http://localhost:" + this.port + "/foo", HttpMethod.GET, request, String.class);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
    String body = entity.getBody();
    assertNotNull("Body was null", body);
    assertTrue("Wrong body: " + body, body.contains("This application has no explicit mapping for /error"));
}

From source file:gateway.test.ServiceTests.java

/**
 * Test GET /service/{serviceId}// w ww.j  a  v  a 2 s .c o  m
 */
@Test
public void testGetMetadata() {
    // Mock
    ServiceResponse mockResponse = new ServiceResponse(mockService);
    when(restTemplate.getForEntity(anyString(), eq(ServiceResponse.class)))
            .thenReturn(new ResponseEntity<ServiceResponse>(mockResponse, HttpStatus.OK));

    // Test
    ResponseEntity<PiazzaResponse> entity = serviceController.getService("123456", user);
    ServiceResponse response = (ServiceResponse) entity.getBody();

    // Verify
    assertTrue(entity.getStatusCode().equals(HttpStatus.OK));
    assertTrue(response.data.getServiceId().equalsIgnoreCase("123456"));
    assertTrue(response.data.getResourceMetadata().getName().equalsIgnoreCase("Test"));

    // Test Exception
    when(restTemplate.getForEntity(anyString(), eq(ServiceResponse.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
    entity = serviceController.getService("123456", user);
    assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(entity.getBody() instanceof ErrorResponse);
}

From source file:com.haulmont.restapi.service.QueriesControllerManager.java

protected String _getCount(String entityName, String queryName, String version, Map<String, String> params) {
    entityName = restControllerUtils.transformEntityNameIfRequired(entityName, version,
            JsonTransformationDirection.FROM_VERSION);
    LoadContext<Entity> ctx;
    try {/*w  ww  . ja  va2 s  .  c o m*/
        ctx = createQueryLoadContext(entityName, queryName, null, null, params);
    } catch (ClassNotFoundException | ParseException e) {
        throw new RestAPIException("Error on executing the query", e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
    long count = dataManager.getCount(ctx);
    return String.valueOf(count);
}

From source file:gateway.test.EventTests.java

/**
 * Test GET /event/{eventId}/* w w  w .  j a va2s . c  o  m*/
 */
@Test
public void testGetEvent() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("event");

    // Test
    ResponseEntity<?> response = eventController.getEventInformation("eventId", user);

    // Verify
    assertTrue(response.getBody().toString().equals("event"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test REST Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.getEventInformation("eventId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.getEventInformation("eventId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));
}

From source file:de.steilerdev.myVerein.server.controller.user.MessageController.java

/**
 * This function sends a message to a specific group chat. The function is invoked by POSTing to the URI /api/user/message.
 * @param currentUser The currently logged in user.
 * @param division The name of the division where the message is send to.
 * @param content The content of the message.
 * @return An HTTP response with a status code. If no error occurred the system wide used id and timestamp are returned. The timestamp is set to the time or receiving on the server, to ensure the same view on the total order of messages for everyone.
 *///w  w w.j a v  a  2s . c om
@RequestMapping(produces = "application/json", method = RequestMethod.POST)
public ResponseEntity<Message> sendMessage(@CurrentUser User currentUser, @RequestParam String division,
        @RequestParam String content, @RequestParam(required = false) String timestamp) {
    logger.trace("[{}] Sending message to {}", currentUser, division);
    Division receivingDivision;
    if (division.isEmpty() || content.isEmpty()) {
        logger.warn("[{}] Required parameters for sending message missing", currentUser);
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } else if ((receivingDivision = divisionRepository.findById(division)) == null) {
        logger.warn("[{}] Unable to find receiving division {}", currentUser, division);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else if (!currentUser.getDivisions().contains(receivingDivision)) {
        logger.warn("[{}] Trying to send a message to a division the user is not part of: {}", currentUser,
                division);
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } else {
        if (receivingDivision.getMemberList().isEmpty()) {
            logger.warn("[{}] Empty receiver list", currentUser);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } else {
            Message message = new Message(content, currentUser, receivingDivision);
            messageRepository.save(message);
            logger.info("[{}] Successfully saved and send message", currentUser);
            return new ResponseEntity<>(message.getSendingObjectOnlyIdAndTimestamp(), HttpStatus.OK);
        }
    }
}

From source file:gateway.controller.AdminController.java

/**
 * Returns a user's UUID for subsequent authentication with pz-gateway endpoints.
 * //from   w  ww.  j a v a  2 s.  com
 * @return Component information
 */
@RequestMapping(value = "/key", method = RequestMethod.GET)
public ResponseEntity<PiazzaResponse> getUUIDForUser() {
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", request.getHeader("Authorization"));
        try {
            return new ResponseEntity<PiazzaResponse>(
                    new RestTemplate()
                            .exchange(SECURITY_URL + "/key", HttpMethod.GET,
                                    new HttpEntity<String>("parameters", headers), UUIDResponse.class)
                            .getBody(),
                    HttpStatus.CREATED);
        } catch (HttpClientErrorException | HttpServerErrorException hee) {
            LOGGER.error(hee.getResponseBodyAsString(), hee);
            return new ResponseEntity<PiazzaResponse>(
                    gatewayUtil.getErrorResponse(hee.getResponseBodyAsString()), hee.getStatusCode());
        }
    } catch (Exception exception) {
        String error = String.format("Error retrieving UUID: %s", exception.getMessage());
        LOGGER.error(error, exception);
        logger.log(error, PiazzaLogger.ERROR);
        return new ResponseEntity<PiazzaResponse>(new ErrorResponse(error, "Gateway"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:gateway.test.DeploymentTests.java

/**
 * Test GET /deployment/*from   ww  w.jav a 2 s .  c o  m*/
 */
@Test
public void testGetList() {
    // Mock
    DeploymentListResponse mockResponse = new DeploymentListResponse();
    mockResponse.data = new ArrayList<Deployment>();
    mockResponse.getData().add(mockDeployment);
    mockResponse.pagination = new Pagination(1, 0, 10, "test", "asc");
    when(restTemplate.getForEntity(anyString(), eq(DeploymentListResponse.class)))
            .thenReturn(new ResponseEntity<DeploymentListResponse>(mockResponse, HttpStatus.OK));

    // Test
    ResponseEntity<PiazzaResponse> entity = deploymentController.getDeployment(null, 0, 10, "asc", "test",
            user);
    PiazzaResponse response = entity.getBody();

    // Verify
    assertTrue(response instanceof DeploymentListResponse);
    DeploymentListResponse dataList = (DeploymentListResponse) response;
    assertTrue(dataList.getData().size() == 1);
    assertTrue(dataList.getPagination().getCount() == 1);
    assertTrue(entity.getStatusCode().equals(HttpStatus.OK));

    // Test Exception
    when(restTemplate.getForEntity(anyString(), eq(DeploymentListResponse.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
    entity = deploymentController.getDeployment(null, 0, 10, "asc", "test", user);
    response = entity.getBody();
    assertTrue(response instanceof ErrorResponse);
    assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:cn.org.once.cstack.config.RestHandlerException.java

@ExceptionHandler(value = { IllegalArgumentException.class })
protected ResponseEntity<Object> handleIllegalArgumentException(Exception ex, WebRequest request) {
    ex.printStackTrace();//from  w  w w .  j  av  a  2 s.c  o  m
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(ex, new HttpErrorServer(ex.getMessage()), headers,
            HttpStatus.INTERNAL_SERVER_ERROR, request);
}

From source file:org.n52.sps.control.admin.AdminControl.java

@RequestMapping(value = DELETE_RESOURCE, method = RequestMethod.POST, headers = "content-type=application/xml; text/xml")
public ModelAndView deleteSensorRequest(InputStream payload, HttpServletResponse response)
        throws InternalServiceException {
    ModelAndView mav = new ModelAndView("xmlview", "response", null);
    OwsExceptionReport exceptionReport = new OwsExceptionReport(); // re-use reporting concept
    try {/*from ww  w.jav a  2 s.co  m*/
        if (!service.isSpsAdminAvailable()) {
            LOGGER.error("delete (SensorOffering)");
            throw new NoApplicableCodeException(OwsException.BAD_REQUEST);
        } else {
            XmlObject request = parseIncomingXmlObject(payload);
            //                if (request.schemaType() ==) {
            //                    
            //                }
            SpsAdmin spsAdminOperator = service.getSpsAdmin();
            spsAdminOperator.deleteSensorOffering(request, exceptionReport);
            mav.addObject(getSuccessResponse());
            response.setStatus(HttpStatus.OK.value());
        }
    } catch (XmlException e) {
        LOGGER.error("Could not parse request.", e);
        exceptionReport.addOwsException(new InvalidRequestException(e.getMessage()));
    } catch (IOException e) {
        LOGGER.error("Could not read request.", e);
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        exceptionReport.addOwsException(new NoApplicableCodeException(code));
    } catch (OwsException e) {
        LOGGER.info("Could not handle POST request.", e);
        exceptionReport.addOwsException(e);
    }
    handleServiceExceptionReport(response, mav, exceptionReport);
    response.setContentType("application/xml");
    return mav;
}

From source file:gateway.test.JobTests.java

/**
 * Test DELETE /job/{jobId}//from  www .  jav  a  2s .co  m
 */
@Test
public void testAbort() {
    // Mock
    ResponseEntity<SuccessResponse> mockEntity = new ResponseEntity<SuccessResponse>(
            new SuccessResponse("Deleted", "Job Manager"), HttpStatus.OK);
    when(restTemplate.postForEntity(anyString(), any(), eq(SuccessResponse.class))).thenReturn(mockEntity);

    // Test
    ResponseEntity<PiazzaResponse> entity = jobController.abortJob("123456", "Not Needed", user);

    // Verify
    assertTrue(entity.getStatusCode().equals(HttpStatus.OK));

    // Test Exception
    when(restTemplate.postForEntity(anyString(), any(), eq(SuccessResponse.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    entity = jobController.abortJob("123456", "Not Needed", user);
    assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(entity.getBody() instanceof ErrorResponse);
}