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:com.cloudbees.jenkins.plugins.demo.actuator.SampleActuatorApplicationTests.java

@Test
public void testErrorPageDirectAccess() throws Exception {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate().getForEntity("http://localhost:" + this.port + "/error",
            Map.class);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> body = entity.getBody();
    assertEquals("None", body.get("error"));
    assertEquals(999, body.get("status"));
}

From source file:gateway.test.EventTests.java

/**
 * Test GET /eventType//w w  w . j  a  va  2s.c o m
 */
@Test
public void testEventTypes() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("eventTypes");

    // Test
    ResponseEntity<?> response = eventController.getEventTypes(null, null, null, 0, 10, user);

    // Verify
    assertTrue(response.getBody().toString().equals("eventTypes"));
    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,
                    WORKFLOW_ERROR.getBytes(), Charset.defaultCharset()));
    response = eventController.getEventTypes(null, null, null, 0, 10, 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.getEventTypes(null, null, null, 0, 10, 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:gateway.test.DeploymentTests.java

/**
 * Test GET /deployment/{deploymentId}//from   w  ww .  j ava 2 s.c  om
 */
@Test
public void testGetMetadata() {
    // Mock the Response
    DeploymentResponse mockResponse = new DeploymentResponse(mockDeployment, "Now");
    when(restTemplate.getForEntity(anyString(), eq(DeploymentResponse.class)))
            .thenReturn(new ResponseEntity<DeploymentResponse>(mockResponse, HttpStatus.OK));

    // Test
    ResponseEntity<PiazzaResponse> entity = deploymentController.getDeployment("123456", user);
    PiazzaResponse response = entity.getBody();

    // Verify
    assertTrue(response instanceof ErrorResponse == false);
    assertTrue(((DeploymentResponse) response).data.getDeployment().getDeploymentId()
            .equalsIgnoreCase(mockDeployment.getDeploymentId()));
    assertTrue(entity.getStatusCode().equals(HttpStatus.OK));

    // Test an Exception
    when(restTemplate.getForEntity(anyString(), eq(DeploymentResponse.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
    entity = deploymentController.getDeployment("123456", user);
    response = entity.getBody();
    assertTrue(response instanceof ErrorResponse);
    assertTrue(entity.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.orange.ngsi.client.UpdateContextRequestTest.java

@Test(expected = HttpServerErrorException.class)
public void dperformPostWith500() throws Exception {

    protocolRegistry.unregisterHost(brokerUrl);

    this.mockServer.expect(requestTo(brokerUrl + "/ngsi10/updateContext")).andExpect(method(HttpMethod.POST))
            .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    ngsiClient.updateContext(brokerUrl, null, createUpdateContextTempSensor(0)).get();
}

From source file:com.esri.geoportal.harvester.rest.TaskController.java

/**
 * Gets task by id.//from   www.j  a  v a  2  s .  c  om
 *
 * @param taskId task id
 * @return task info or <code>null</code> if no task found
 */
@RequestMapping(value = "/rest/harvester/tasks/{taskId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TaskResponse> getTask(@PathVariable UUID taskId) {
    try {
        LOG.debug(formatForLog("GET /rest/harvester/tasks/%s", taskId));
        TaskDefinition taskDefinition = engine.getTasksService().readTaskDefinition(taskId);
        if (taskDefinition == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(new TaskResponse(taskId, taskDefinition), HttpStatus.OK);
    } catch (DataProcessorException ex) {
        LOG.error(formatForLog("Error getting task: %s", taskId), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

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

@RequestMapping(produces = "application/json", params = { "id", "response" }, method = RequestMethod.GET)
public ResponseEntity<List<String>> getResponsesOfEvent(@RequestParam(value = "response") String responseString,
        @RequestParam(value = "id") String eventID, @CurrentUser User currentUser) {
    logger.debug("[{}] Finding all responses of type {} to event {}", currentUser, responseString, eventID);
    Event event;/*from   ww w  . j  a  v a 2 s  .c  o m*/
    if (eventID.isEmpty()) {
        logger.warn("[{}] The event id is not allowed to be empty", currentUser);
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    } else if ((event = eventRepository.findEventById(eventID)) == null) {
        logger.warn("[{}] Unable to gather the specified event with id {}", currentUser, eventID);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        EventStatus response;
        try {
            response = EventStatus.valueOf(responseString.toUpperCase());
        } catch (IllegalArgumentException e) {
            logger.warn("[{}] Unable to parse response: {}", currentUser, e.getLocalizedMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        if (!event.getInvitedUser().containsKey(currentUser.getId())) {
            logger.warn("[{}] User is not invited to the event");
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } else {
            // Filtering invited user matching the response
            HashMap<String, EventStatus> invitedUser = new HashMap<>(event.getInvitedUser());
            List<String> matchingUser = invitedUser.keySet().stream()
                    .filter(userID -> invitedUser.get(userID) == response).collect(Collectors.toList());

            logger.info("[{}] Successfully gathered all user matching the response {} for event {}",
                    currentUser, response, event);
            return new ResponseEntity<>(matchingUser, HttpStatus.OK);
        }
    }
}

From source file:gateway.controller.EventController.java

/**
 * Gets all Events from the workflow component.
 * /*w  w  w.  j ava2s  . c o m*/
 * @see http://pz-swagger.stage.geointservices.io/#!/Event/get_event
 * 
 * @param user
 *            The user submitting the request
 * @return The list of Events, or the appropriate error.
 */
@RequestMapping(value = "/event", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get all Events", notes = "Retrieves a list of all Events", tags = { "Event",
        "Workflow" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of Events.", response = EventListResponse.class),
        @ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = ErrorResponse.class),
        @ApiResponse(code = 500, message = "Internal Error", response = ErrorResponse.class) })
public ResponseEntity<?> getEvents(
        @ApiParam(value = "The name of the EventType to filter by.") @RequestParam(value = "eventTypeName", required = false) String eventTypeName,
        @ApiParam(value = "The Id of the EventType to filter by.") @RequestParam(value = "eventTypeId", required = false) String eventTypeId,
        @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false, defaultValue = DEFAULT_ORDER) String order,
        @ApiParam(value = "The data field to sort by.") @RequestParam(value = "sortBy", required = false, defaultValue = DEFAULT_SORTBY) String sortBy,
        @ApiParam(value = "Paginating large numbers of results. This will determine the starting page for the query.") @RequestParam(value = "page", required = false, defaultValue = DEFAULT_PAGE) Integer page,
        @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "perPage", required = false, defaultValue = DEFAULT_PAGE_SIZE) Integer perPage,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s queried for Events.", gatewayUtil.getPrincipalName(user)),
                PiazzaLogger.INFO);

        // Validate params
        String validationError = null;
        if ((order != null && (validationError = gatewayUtil.validateInput("order", order)) != null)
                || (page != null && (validationError = gatewayUtil.validateInput("page", page)) != null)
                || (perPage != null
                        && (validationError = gatewayUtil.validateInput("perPage", perPage)) != null)) {
            return new ResponseEntity<PiazzaResponse>(new ErrorResponse(validationError, "Gateway"),
                    HttpStatus.BAD_REQUEST);
        }

        try {
            // Broker the request to Workflow
            String url = String.format(
                    "%s/%s?page=%s&perPage=%s&order=%s&sortBy=%s&eventTypeName=%s&eventTypeId=%s", WORKFLOW_URL,
                    "event", page, perPage, order, sortBy != null ? sortBy : "",
                    eventTypeName != null ? eventTypeName : "", eventTypeId != null ? eventTypeId : "");
            return new ResponseEntity<String>(restTemplate.getForEntity(url, String.class).getBody(),
                    HttpStatus.OK);
        } catch (HttpClientErrorException | HttpServerErrorException hee) {
            LOGGER.error(hee.getMessage(), hee);
            return new ResponseEntity<PiazzaResponse>(
                    gatewayUtil.getErrorResponse(
                            hee.getResponseBodyAsString().replaceAll("}", " ,\"type\":\"error\" }")),
                    hee.getStatusCode());
        }
    } catch (Exception exception) {
        String error = String.format("Error Querying Events by user %s: %s", gatewayUtil.getPrincipalName(user),
                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:storage.StorageServiceWrapperController.java

protected ResponseEntity<String> read(@Nonnull final String storageServiceId, @Nonnull final String context,
        @Nonnull final String key) {
    try {//from w  w  w .j  a v a 2 s .  com
        final StorageService storageService = getStorageService(storageServiceId);
        if (storageService == null) {
            log.debug("Unable to find storage service with id '{}'", storageServiceId);
            return seleniumFriendlyResponse(HttpStatus.BAD_REQUEST);
        }

        log.debug("Reading from '{}' with context '{}' and key '{}'", storageServiceId, context, key);
        final StorageRecord record = storageService.read(context, key);
        log.debug("Read '{}' from '{}' with context '{}' and key '{}'", record, storageServiceId, context, key);

        if (record == null) {
            return seleniumFriendlyResponse(HttpStatus.NOT_FOUND);
        } else {
            final String serializedStorageRecord = serializer.serialize(record);
            final HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity<>(serializedStorageRecord, httpHeaders, HttpStatus.OK);
        }
    } catch (IOException e) {
        log.debug("An error occurred", e);
        return seleniumFriendlyResponse(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:be.solidx.hot.rest.RestController.java

protected ResponseEntity<byte[]> buildResponse(byte[] response, HttpHeaders httpHeaders, Integer httpStatus) {
    try {/*ww w . j  av  a2  s. c  o  m*/
        return new ResponseEntity<byte[]>(response, httpHeaders, HttpStatus.valueOf(httpStatus));
    } catch (ScriptException e) {
        return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java

/**
 * Uploads a image to the solution and updates the solution data with
 * the name of the file being uploaded. Returns a <b>403 Forbidden</b> if
 * the logged in user is not the owner of the solution.
 *///from   w  w w  . j  a  v  a2s.  co  m
@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload-image")
public ResponseEntity<String> uploadImage(Principal principal, @RequestParam("id") Long id,
        @RequestParam("file") MultipartFile file) throws Exception {
    // verify that we have the correct owner
    Account account = accountRepository.findOne(principal.getName());
    if (!canEdit(principal, id)) {
        return new ResponseEntity<String>("Logged in user is not the owner of the solution",
                HttpStatus.FORBIDDEN);
    }
    fileService.saveSolutionFile(id, file);
    // get solution and update with new information
    Node node = marketplaceDAO.getSolution(id);
    node.setImage(file.getOriginalFilename());
    Object result = marketplaceDAO.saveOrUpdateSolution(node, account);
    if (result instanceof Node) {
        return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK);
    } else {
        return new ResponseEntity<String>((String) result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}