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:gateway.controller.DataController.java

/**
 * Returns a queried list of Data Resources previously loaded into Piazza.
 * //from w w w . j  a  v a 2 s . c  om
 * @see http://pz-swagger.stage.geointservices.io/#!/Data/get_data
 * 
 * @param user
 *            The user making the request
 * @return The list of results, with pagination information included. ErrorResponse if something goes wrong.
 */
@RequestMapping(value = "/data", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Query Piazza Data", notes = "Sends a simple GET Query for fetching lists of Piazza Data.", tags = "Data")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of Search results that match the query string.", response = DataResourceListResponse.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<PiazzaResponse> getData(
        @ApiParam(value = "A general keyword search to apply to all Datasets.") @RequestParam(value = "keyword", required = false) String keyword,
        @ApiParam(value = "Filter datasets that were created by a specific Job Id.") @RequestParam(value = "createdByJobId", required = false) String createdByJobId,
        @ApiParam(value = "Paginating large datasets. 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,
        @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 = "Filter for the username that published the service.") @RequestParam(value = "createdBy", required = false) String createdBy,
        Principal user) {
    try {
        // Log the request
        // logger.log(String.format("User %s requested Data List query.", 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);
        }

        // Proxy the request to Pz-Access
        String url = String.format("%s/%s?page=%s&perPage=%s", ACCESS_URL, "data", page, perPage);
        // Attach keywords if specified
        if ((keyword != null) && (keyword.isEmpty() == false)) {
            url = String.format("%s&keyword=%s", url, keyword);
        }
        // Add username if specified
        if ((createdBy != null) && (createdBy.isEmpty() == false)) {
            url = String.format("%s&userName=%s", url, createdBy);
        }
        // Add optional pagination
        if ((order != null) && (order.isEmpty() == false)) {
            url = String.format("%s&order=%s", url, order);
        }
        if ((sortBy != null) && (sortBy.isEmpty() == false)) {
            url = String.format("%s&sortBy=%s", url, sortBy);
        }
        if ((createdByJobId != null) && (createdByJobId.isEmpty() == false)) {
            url = String.format("%s&createdByJobId=%s", url, createdByJobId);
        }
        try {
            return new ResponseEntity<PiazzaResponse>(
                    restTemplate.getForEntity(url, DataResourceListResponse.class).getBody(), HttpStatus.OK);
        } catch (HttpClientErrorException | HttpServerErrorException hee) {
            LOGGER.error("Error querying data.", hee);
            return new ResponseEntity<PiazzaResponse>(
                    gatewayUtil.getErrorResponse(hee.getResponseBodyAsString()), hee.getStatusCode());
        }
    } catch (Exception exception) {
        String error = String.format("Error Querying Data 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:ca.hec.tenjin.tool.controller.SyllabusController.java

@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody Object handleStructureSyllabusException(StructureSyllabusException ex) {
    ex.printStackTrace();/*ww w.  j av a 2 s  .c  om*/
    return null;
}

From source file:gateway.test.EventTests.java

/**
 * Test POST /eventType/*from   ww w  .  j  a va  2 s  . co m*/
 */
@Test
public void testCreateEventType() {
    // Mock Response
    when(restTemplate.postForObject(anyString(), any(), eq(String.class))).thenReturn("OK");

    // Test
    ResponseEntity<?> response = eventController.createEventType(new EventType(), user);

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

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

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

/**
 * Gets task by id.//w  ww  . ja  va  2 s  .  c  o m
 *
 * @param taskId task id
 * @return task info or <code>null</code> if no task found
 */
@RequestMapping(value = "/rest/harvester/tasks/{taskId}/export", method = RequestMethod.GET)
public ResponseEntity<String> export(@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);
        }
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-disposition", String.format("attachment; filename=\"%s.json\"", taskId));
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(mapper.writeValueAsString(taskDefinition),
                headers, HttpStatus.OK);
        return responseEntity;
    } catch (DataProcessorException | JsonProcessingException ex) {
        LOG.error(formatForLog("Error getting task: %s", taskId), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:it.polimi.diceH2020.launcher.controller.rest.RestLaunchAnalysisController.java

@RequestMapping(value = "/submit/{id}", method = RequestMethod.POST)
public ResponseEntity<BaseResponseBody> submitById(@PathVariable Long id) {
    BaseResponseBody body = new BaseResponseBody();

    PendingSubmission submission = submissionRepository.findOne(id);

    if (submission == null) {
        body.setMessage(String.format("A submission with ID %d is not pending", id));
        return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
    }//from w  w w .j a  v a2 s . c o  m

    Scenario scenario = submission.getScenario();
    body.setScenario(scenario);

    List<String> pathList = submission.getPaths();

    if (pathList == null || pathList.isEmpty()) {
        cleanup(id, null);
        String message = "You haven't submitted any file!";
        logger.error(message);
        body.setMessage(message);
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    String instanceDataMultiProviderPath = submission.getInstanceData();
    if (instanceDataMultiProviderPath == null) {
        cleanup(id, null);
        String message = "Select a Json file!";
        logger.error(message);
        body.setMessage(message);
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    Optional<InstanceDataMultiProvider> maybeInstanceData = validator
            .readInstanceDataMultiProvider(Paths.get(instanceDataMultiProviderPath));

    if (maybeInstanceData.isPresent()) {
        if (!maybeInstanceData.get().validate()) {
            cleanup(id, null);
            String message = maybeInstanceData.get().getValidationError();
            logger.error(message);
            body.setMessage(message);
            return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
        }
    } else {
        cleanup(id, null);
        String message = "Error with InstanceDataMultiProvider";
        logger.error(message);
        body.setMessage(message);
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    InstanceDataMultiProvider instanceDataMultiProvider = maybeInstanceData.get();
    instanceDataMultiProvider.setScenario(scenario);

    String check = scenarioValidation(instanceDataMultiProvider);
    if (!check.equals("ok")) {
        cleanup(id, null);
        logger.error(check);
        body.setMessage(check);
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    List<InstanceDataMultiProvider> inputList = JsonSplitter
            .splitInstanceDataMultiProvider(instanceDataMultiProvider);

    if (inputList.size() > 1) {
        List<String> providersList = inputList.stream().map(InstanceDataMultiProvider::getProvider)
                .filter(Objects::nonNull).collect(Collectors.toList());
        if (!minNumTxt(providersList, pathList)) {
            cleanup(id, null);
            String message = "Not enough TXT files selected.\nFor each provider in your JSON there must be 2 TXT files containing in their name the provider name.";
            logger.error(message);
            body.setMessage(message);
            return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
        }
    }

    List<SimulationsManager> simManagerList = initializeSimManagers(inputList);
    List<File> generatedFiles = new ArrayList<>();

    for (SimulationsManager sm : simManagerList) {
        sm.setInputFileName(Paths.get(instanceDataMultiProviderPath).getFileName().toString());
        InstanceDataMultiProvider input = sm.getInputData();

        File txtFolder;
        try {
            txtFolder = fileUtility.createInputSubFolder();
            generatedFiles.add(txtFolder);
        } catch (FileNameClashException e) {
            cleanup(id, generatedFiles);
            String message = "Too many folders for TXTs with the same name have been created!";
            logger.error(message, e);
            body.setMessage(message);
            return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            cleanup(id, generatedFiles);
            String message = "Could not create a folders for TXTs!";
            logger.error(message, e);
            body.setMessage(message);
            return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        for (Map.Entry<String, Map<String, Map<String, JobProfile>>> jobIDs : input.getMapJobProfiles()
                .getMapJobProfile().entrySet()) {
            for (Map.Entry<String, Map<String, JobProfile>> provider : jobIDs.getValue().entrySet()) {
                for (Map.Entry<String, JobProfile> typeVMs : provider.getValue().entrySet()) {

                    String secondPartOfTXTName = getSecondPartOfReplayerFileName(jobIDs.getKey(),
                            provider.getKey(), typeVMs.getKey());

                    List<String> txtToBeSaved = pathList.stream().filter(s -> s.contains(secondPartOfTXTName))
                            .filter(s -> s.contains(input.getId())).collect(Collectors.toList());

                    if (txtToBeSaved.isEmpty()) {
                        cleanup(id, generatedFiles);
                        String message = String.format(
                                "Missing TXT file for Instance: %s, Job: %s, Provider: %s, TypeVM: %s",
                                input.getId(), jobIDs.getKey(), provider.getKey(), typeVMs.getKey());
                        logger.error(message);
                        body.setMessage(message);
                        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
                    }

                    for (String srcPath : txtToBeSaved) {
                        File src = new File(srcPath);

                        String fileContent;
                        try (FileReader reader = new FileReader(src)) {
                            fileContent = IOUtils.toString(reader);
                            String compressedContent = Compressor.compress(fileContent);

                            File generatedFile = fileUtility.createInputFile(txtFolder, src.getName());
                            fileUtility.writeContentToFile(compressedContent, generatedFile);

                            generatedFiles.add(generatedFile);
                        } catch (FileNameClashException e) {
                            cleanup(id, generatedFiles);
                            body.setMessage(e.getMessage());
                            logger.error("Cannot create file due to filename clash", e);
                            return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
                        } catch (IOException e) {
                            cleanup(id, generatedFiles);
                            String message = String.format(
                                    "Problem with TXT paths. [TXT file for Instance: %s, Job: %s, Provider: %s, TypeVM: %s]",
                                    input.getId(), jobIDs.getKey(), provider.getKey(), typeVMs.getKey());
                            logger.error(message, e);
                            body.setMessage(message);
                            return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
                        }

                        if (fileContent.isEmpty()) {
                            cleanup(id, generatedFiles);
                            String message = String.format(
                                    "Missing TXT file content for Instance: %s, Job: %s, Provider: %s, TypeVM: %s",
                                    input.getId(), jobIDs.getKey(), provider.getKey(), typeVMs.getKey());
                            logger.error(message);
                            body.setMessage(message);
                            return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
                        }
                    }
                }
            }
        }

        sm.addInputFolder(txtFolder.getPath());
        sm.setNumCompletedSimulations(0);
        sm.buildExperiments();
    }

    cleanup(id, null);

    for (SimulationsManager simulationsManager : simManagerList) {
        logger.trace("Simulation with " + simulationsManager.toString() + " - Scenario is "
                + simulationsManager.getScenario().getStringRepresentation());
        diceService.simulation(simulationsManager);

        Link link = ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(DownloadsController.class)
                .downloadSolutionJson(simulationsManager.getId())).withRel("solution");
        body.add(link);
    }

    return new ResponseEntity<>(body, HttpStatus.OK);
}

From source file:de.hska.ld.oidc.controller.DiscussionController.java

/**
 * @param documentId//from  w  w  w .ja v a 2  s  . c  o m
 * @param discRequestDto {
 *                       description: ""
 *                       label: "Test"
 *                       tags: []
 *                       }
 * @return
 */
@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST, value = "/document/{documentId}/discussion")
public ResponseEntity createDiscussion(@PathVariable String documentId,
        @RequestBody SSSCreateDiscRequestDto discRequestDto) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    OIDCAuthenticationToken token = (OIDCAuthenticationToken) auth;
    SSSCreateDiscResponseDto sssCreateDiscResponseDto = null;
    // remove tag list because the sss doesn't know how to process this
    List<String> tagList = discRequestDto.getTags();
    discRequestDto.setTags(null);

    try {
        String episodeId = null;
        try {
            Document document = documentService.findById(Long.parseLong(documentId));
            if (document != null) {
                DocumentSSSInfo documentSSSInfo = documentSSSInfoService.getDocumentSSSInfo(document);
                if (documentSSSInfo != null) {
                    episodeId = documentSSSInfo.getEpisodeId();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sssCreateDiscResponseDto = sssClient.createDiscussion(documentId, discRequestDto,
                token.getAccessTokenValue(), episodeId);
        try {
            LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
            LoggingContext.put("documentId", EscapeUtil.escapeJsonForLogging(documentId.toString()));
            LoggingContext.put("sssDiscussionLabel",
                    EscapeUtil.escapeJsonForLogging(sssCreateDiscResponseDto.getDisc()));
            Logger.trace("User created discussion.");
        } catch (Exception e) {
            Logger.error(e);
        } finally {
            LoggingContext.clear();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    if (tagList != null && tagList.size() > 0) {
        for (String tag : tagList) {
            try {
                sssClient.addTagTo(sssCreateDiscResponseDto.getDisc(), tag, token.getAccessTokenValue());
            } catch (Exception e) {
                e.printStackTrace();
                return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }
    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:com.mycompany.projetsportmanager.spring.rest.controllers.UserController.java

/**
 * Affect a image to a specified user/*www  .j av  a  2 s.c o  m*/
 * 
 * @param userId
 *            the user identifier
 * @param uploadedInputStream
 *            the image uploaded input stream
 * @param fileDetail
 *            the image detail format
 * @return response
 */
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/picture")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(value = "hasRole('AK_ADMIN')")
public void pictureUpdate(@PathVariable("userId") Long userId, @RequestParam MultipartFile user_picture) {

    //Le nom du paramtre correspond au nom du champ de formulaire qu'il faut utiliser !!!!

    if (user_picture == null || user_picture.isEmpty()) {
        logger.debug("Incorrect input stream or file name for image of user" + userId);
        throw new DefaultSportManagerException(new ErrorResource("parameter missing",
                "Picture should be uploaded as a multipart/form-data file param named user_picture",
                HttpStatus.BAD_REQUEST));
    }

    if (!(user_picture.getOriginalFilename().endsWith(".jpg")
            || user_picture.getOriginalFilename().endsWith(".jpeg"))) {
        logger.debug("File for picture of user" + userId + " must be a JPEG file.");
        throw new DefaultSportManagerException(new ErrorResource("incorrect file format",
                "Picture should be a JPG file", HttpStatus.BAD_REQUEST));
    }

    try {
        userService.addUserPicture(userId, user_picture.getInputStream());
    } catch (SportManagerException e) {
        String msg = "Can't update user picture with id " + userId + " into DB";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("db error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    } catch (IOException e) {
        String msg = "Can't update user picture with id " + userId + " because of IO Error";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("io error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    }
}

From source file:net.nan21.dnet.core.web.controller.AbstractDnetController.java

/**
 * Generic exception handler/*from  w w  w .  j a  va  2 s  .co m*/
 * 
 * @param e
 * @param response
 * @return
 * @throws IOException
 */
@ExceptionHandler(value = Exception.class)
@ResponseBody
protected String handleException(Exception e, HttpServletResponse response) throws IOException {

    e.printStackTrace();

    if (e instanceof NotAuthorizedRequestException) {
        return this.handleException((NotAuthorizedRequestException) e, response);
    } else if (e instanceof InvocationTargetException) {
        StringBuffer sb = new StringBuffer();
        if (e.getMessage() != null) {
            sb.append(e.getMessage() + "\n");
        }
        Throwable exc = ((InvocationTargetException) e).getTargetException();

        if (exc.getMessage() != null) {
            sb.append(exc.getMessage() + "\n");
        }

        if (exc.getCause() != null) {
            if (sb.length() > 0) {
                sb.append(" Reason: ");
            }
            sb.append(exc.getCause().getLocalizedMessage());
        }

        exc.printStackTrace();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.getOutputStream().print(sb.toString());
        return null;
    }
    StringBuffer sb = new StringBuffer();
    if (e.getLocalizedMessage() != null) {
        sb.append(e.getLocalizedMessage());
    } else if (e.getCause() != null) {
        if (sb.length() > 0) {
            sb.append(" Reason: ");
        }
        sb.append(e.getCause().getLocalizedMessage());
    }
    if (sb.length() == 0) {
        if (e.getStackTrace() != null) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            e.printStackTrace(response.getWriter());
            return null;
        }
    }
    response.setStatus(HttpStatus.EXPECTATION_FAILED.value());
    response.getOutputStream().print(sb.toString());
    response.getOutputStream().flush();
    return null;

}

From source file:com.github.ukase.web.UkaseController.java

@ExceptionHandler(RenderException.class)
@ResponseBody/*  w w  w  .ja  va 2s  .c om*/
public ResponseEntity<String> handleRenderException(RenderException e) {
    log.warn("Rendering: " + e.getMessage(), e.getCause());
    return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}