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.jkratz.igdb.controller.advice.ErrorController.java
@RequestMapping(produces = "application/json") @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public @ResponseBody Map<String, Object> handleUncaughtException(Exception ex) { logger.error("Unhandled Exception", ex); Map<String, Object> map = Maps.newHashMap(); map.put("error", "Generic Error"); map.put("message", ex.getMessage()); if (ex.getCause() != null) { map.put("cause", ex.getCause().getMessage()); }//from w w w . jav a 2s . com return map; }
From source file:be.solidx.hot.rest.RestController.java
protected ResponseEntity<byte[]> buildResponse(Map content, Map headers, Integer httpStatus, Charset requestedEncoding) { try {/*from w w w. ja v a 2 s . c o m*/ HttpHeaders httpHeaders = buildHttpHeaders(headers); List<String> contentType = httpHeaders.get(com.google.common.net.HttpHeaders.CONTENT_TYPE); if (contentType != null && contentType.size() > 0 && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) { return new ResponseEntity<byte[]>(objectMapper.writeValueAsBytes(content), httpHeaders, HttpStatus.valueOf(httpStatus)); } else { return new ResponseEntity<byte[]>(content.toString().getBytes(requestedEncoding), httpHeaders, HttpStatus.valueOf(httpStatus)); } } catch (Exception e) { logger.error("", e); return new ResponseEntity<byte[]>(e.getMessage().toString().getBytes(requestedEncoding), HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:de.steilerdev.myVerein.server.controller.init.InitController.java
License:asdf
/** * This function is temporarily saving the general settings during the initial setup. The values are stored permanently after calling the initSuperAdmin function. This function is invoked by POSTing the parameters to the URI /api/init/settings. * @param clubName The name of the club. * @param databaseHost The hostname of the MongoDB server (Default localhost). * @param databasePort The port of the MongoDB server (Default 27017). * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed). * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed). * @param databaseCollection The name of the database collection (Default myVerein). * @param locale The current locale of the user. * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available. *///from w w w .j a v a 2 s . c o m @RequestMapping(value = "settings", method = RequestMethod.POST) public ResponseEntity<String> initSettings(@RequestParam String clubName, @RequestParam String databaseHost, @RequestParam String databasePort, @RequestParam String databaseUser, @RequestParam String databasePassword, @RequestParam String databaseCollection, Locale locale) { logger.trace("Starting initial settings configuration"); Settings settings = new Settings(); if (!settings.isInitialSetup()) { logger.warn("An initial setup API was used, even though the system is already configured."); return new ResponseEntity<>( messageSource.getMessage("init.message.settings.notAllowed", null, "You are not allowed to perform this action at the moment", locale), HttpStatus.BAD_REQUEST); } else if (clubName.isEmpty()) { logger.warn("The club name is not present"); return new ResponseEntity<>(messageSource.getMessage("init.message.settings.noName", null, "The club name is required", locale), HttpStatus.BAD_REQUEST); } else { int databasePortInt = 27017; if (databaseHost.isEmpty()) { logger.warn("The database host is empty, using default value."); databaseHost = "localhost"; } if (databasePort.isEmpty()) { logger.warn("The database port is empty, using default value."); databasePort = "27017"; } else { try { databasePortInt = Integer.parseInt(databasePort); } catch (NumberFormatException e) { logger.warn("The database port does not seem to be a number " + databasePort + ", " + e.getMessage()); return new ResponseEntity<>(messageSource.getMessage("init.message.settings.dbPortNoNumber", null, "The database port needs to be a number", locale), HttpStatus.BAD_REQUEST); } } if (databaseCollection.isEmpty()) { logger.warn("The database collection name is empty, using default value"); databaseCollection = "myVerein"; } if (!mongoIsAvailable(databaseHost, databasePortInt, databaseUser, databasePassword, databaseCollection)) { logger.warn("The stated MongoDB is not available"); return new ResponseEntity<>(messageSource.getMessage("init.message.settings.mongoNotAvailable", null, "The stated MongoDB is not available", locale), HttpStatus.BAD_REQUEST); } try { logger.debug("Temporarily storing settings information"); settings.setClubName(clubName); settings.setDatabaseHost(databaseHost); settings.setDatabasePort(databasePort); settings.setDatabaseUser(databaseUser); settings.setDatabasePassword(databasePassword); settings.setDatabaseName(databaseCollection); databaseName = databaseCollection; savingInitialSetup(null, null, settings); } catch (IOException e) { logger.warn("Unable to save settings."); return new ResponseEntity<>( messageSource.getMessage("init.message.settings.savingSettingsError", null, "Unable to save settings, please try again", locale), HttpStatus.INTERNAL_SERVER_ERROR); } logger.info("Successfully stored and validated settings information"); return new ResponseEntity<>(messageSource.getMessage("init.message.settings.savingSettingsSuccess", null, "Successfully saved settings", locale), HttpStatus.OK); } }
From source file:gateway.controller.AlertTriggerController.java
/** * Creates a new Trigger//from w w w . j a va 2 s.c om * * @see "http://pz-swagger.stage.geointservices.io/#!/Trigger/post_trigger" * * @param trigger * The Trigger JSON. * @param user * The user making the request * @return The Trigger, or an error. */ @RequestMapping(value = "/trigger", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) @ApiOperation(value = "Creates a Trigger", notes = "Creates a new Trigger", tags = { "Trigger", "Workflow" }) @ApiResponses(value = { @ApiResponse(code = 201, message = "The newly created Trigger", response = TriggerResponse.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<?> createTrigger( @ApiParam(value = "The Trigger information to register. This defines the Conditions that must be hit in order for some Action to occur.", required = true) @Valid @RequestBody Trigger trigger, Principal user) { try { // Log the message logger.log(String.format("User %s has requested a new Trigger to be created.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); try { // Attempt to set the username of the Job in the Trigger to the // submitting username trigger.job.createdBy = gatewayUtil.getPrincipalName(user); trigger.createdBy = gatewayUtil.getPrincipalName(user); } catch (Exception exception) { String message = String.format( "Failed to set the username field in Trigger created by User %s: - exception: %s", gatewayUtil.getPrincipalName(user), exception.getMessage()); LOGGER.warn(message, exception); logger.log(message, PiazzaLogger.WARNING); } try { // Proxy the request to Workflow return new ResponseEntity<String>( restTemplate.postForObject(String.format("%s/%s", WORKFLOW_URL, "trigger"), objectMapper.writeValueAsString(trigger), String.class), HttpStatus.CREATED); } catch (HttpClientErrorException | HttpServerErrorException hee) { LOGGER.error(String.format("Received Code %s with Message %s while creating a Trigger.", hee.getStatusCode().toString(), hee.getMessage()), hee); return new ResponseEntity<PiazzaResponse>( gatewayUtil.getErrorResponse( hee.getResponseBodyAsString().replaceAll("}", " ,\"type\":\"error\" }")), hee.getStatusCode()); } } catch (Exception exception) { String error = String.format("Error Creating Trigger 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:gateway.test.AlertTriggerTests.java
/** * Test GET /alert/{alertId}/*from www. j a va 2 s .c om*/ */ @Test public void testGetAlert() { // Mock Response when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("Alert"); // Test ResponseEntity<?> response = alertTriggerController.getAlert("AlertID", user); // Verify assertTrue(response.getBody().toString().equals("Alert")); assertTrue(response.getStatusCode().equals(HttpStatus.OK)); // Test Exception when(restTemplate.getForObject(anyString(), eq(String.class))) .thenThrow(new RestClientException("Alert Error")); response = alertTriggerController.getAlert("AlertID", user); assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)); assertTrue(response.getBody() instanceof ErrorResponse); assertTrue(((ErrorResponse) response.getBody()).message.contains("Alert Error")); }
From source file:gob.mx.salud.api.util.ResponseWrapper.java
/** * Genera una respuesta fallida del tipo <b>500-INTERNAL_SERVER_ERROR</b> * @param message//from w ww .ja va 2s .c o m * @param data * @return {@code ResponseWrapper<T>} */ @SuppressWarnings("unchecked") public ResponseWrapper<T> failServerError(String message, String data) { fail(ResponseWrapper.FAIL, HttpStatus.INTERNAL_SERVER_ERROR.value(), message, (T) data); return this; }
From source file:gateway.controller.ServiceController.java
/** * Registers an external service with the Piazza Service Controller. * /* ww w .j av a2 s. com*/ * @see http://pz-swagger.stage.geointservices.io/#!/Service/post_service * * @param service * The service to register. * @param user * The user submitting the request * @return The Service Id, or appropriate error. */ @RequestMapping(value = "/service", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) @ApiOperation(value = "Register new Service definition", notes = "Creates a new Service with the Piazza Service Controller; that can be invoked through Piazza jobs with Piazza data.", tags = "Service") @ApiResponses(value = { @ApiResponse(code = 201, message = "The Id of the newly created Service", response = ServiceIdResponse.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> registerService( @ApiParam(value = "The metadata for the service. This includes the URL, parameters, inputs and outputs. It also includes other release metadata such as classification and availability.", required = true) @Valid @RequestBody Service service, Principal user) { try { // Log the request logger.log(String.format("User %s requested Service registration.", gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO); // Populate the authoring field in the Service Metadata if (service.getResourceMetadata() == null) { service.setResourceMetadata(new ResourceMetadata()); } service.getResourceMetadata().createdBy = gatewayUtil.getPrincipalName(user); service.getResourceMetadata().createdOn = (new DateTime()).toString(); // Create the Service Job to forward PiazzaJobRequest jobRequest = new PiazzaJobRequest(); jobRequest.createdBy = gatewayUtil.getPrincipalName(user); jobRequest.jobType = new RegisterServiceJob(service); // Proxy the request to the Service Controller try { return new ResponseEntity<PiazzaResponse>( restTemplate.postForEntity(String.format("%s/%s", SERVICECONTROLLER_URL, "registerService"), jobRequest, ServiceIdResponse.class).getBody(), HttpStatus.CREATED); } catch (HttpClientErrorException | HttpServerErrorException hee) { LOGGER.error("Error Registering Service", hee); return new ResponseEntity<PiazzaResponse>( gatewayUtil.getErrorResponse(hee.getResponseBodyAsString()), hee.getStatusCode()); } } catch (Exception exception) { String error = String.format("Error Registering Service 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:com.javafxpert.wikibrowser.WikiVisGraphController.java
/** * Retrieve all paths through any properties, with a length of one or two hops, between two given item IDs. * TODO: Consider adding a LIMIT parameter * @param itemId// w w w . ja v a 2 s .co m * @param targetId * @return */ @RequestMapping(value = "/visshortpaths", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Object> retrieveShortPaths(@RequestParam(value = "id", defaultValue = "Q1") String itemId, @RequestParam(value = "target", defaultValue = "Q323") String targetId) { // Example endpoint usage is shortpaths?id=Q23&target=Q9696 VisGraphResponseNear visGraphResponseNear = null; String neoCypherUrl = wikiBrowserProperties.getNeoCypherUrl(); /* Example Cypher query POST { "statements" : [ { "statement" : "MATCH p=allShortestPaths( (a:Item {itemId:'Q23'})-[*..2]-(b:Item {itemId:'Q9696'}) ) RETURN p", "resultDataContents" : ["graph" ] } ] } */ /* MATCH p=allShortestPaths( (a:Item {itemId:'Q23'})-[*..2]-(b:Item {itemId:'Q9696'}) ) RETURN p LIMIT 200 */ String qa = "{\"statements\":[{\"statement\":\"MATCH p=allShortestPaths( (a:Item {itemId:'"; String qb = itemId; // starting item ID String qc = "'})-[*..2]-(b:Item {itemId:'"; String qd = targetId; // target item ID String qe = "'}) ) WHERE NONE(x IN NODES(p) WHERE x:Item AND x.itemId = 'Q5') "; // Don't return paths that contain human item ID, or described by relationships String qf = "AND NONE(y IN RELATIONSHIPS(p) WHERE y.propId = 'P1343') RETURN p LIMIT 200\","; String qg = "\"resultDataContents\":[\"graph\"]}]}"; String postString = qa + qb + qc + qd + qe + qf + qg; visGraphResponseNear = queryProcessSearchResponse(neoCypherUrl, postString); return Optional.ofNullable(visGraphResponseNear).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK)) .orElse(new ResponseEntity<>("visshortpaths query unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR)); }
From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java
/** * Updates the Status for a Piazza Job.//from w w w . j a v a 2 s . co m * * @param userName * The name of the user. Used for verification. * @param serviceId * The ID of the Service containing the Job * @param jobId * The ID of the Job to update * @param statusUpdate * The update contents, including status, percentage, and possibly results. * @return Success or error. */ @RequestMapping(value = { "/service/{serviceId}/task/{jobId}" }, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PiazzaResponse> updateServiceJobStatus( @RequestParam(value = "userName", required = true) String userName, @PathVariable(value = "serviceId") String serviceId, @PathVariable(value = "jobId") String jobId, @RequestBody StatusUpdate statusUpdate) { try { // Log the Request piazzaLogger.log( String.format("User %s Requesting to Update Job Status for Job %s for Task-Managed Service.", userName, jobId), Severity.INFORMATIONAL); // Check for Access boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName); if (!canAccess) { throw new ResourceAccessException("Service does not allow this user to access."); } // Simple Validation if ((statusUpdate.getStatus() == null) || (statusUpdate.getStatus().isEmpty())) { throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "`status` property must be provided in Update payload."); } // Process the Update serviceTaskManager.processStatusUpdate(serviceId, jobId, statusUpdate); // Return Success return new ResponseEntity<>(new SuccessResponse("OK", "ServiceController"), HttpStatus.OK); } catch (Exception exception) { String error = String.format("Could not Update status for Job %s for Service %s : %s", jobId, serviceId, exception.getMessage()); LOGGER.error(error, exception); piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "failedToUpdateServiceJob", jobId)); HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; if (exception instanceof ResourceAccessException) { status = HttpStatus.UNAUTHORIZED; } else if (exception instanceof InvalidInputException) { status = HttpStatus.NOT_FOUND; } else if (exception instanceof HttpServerErrorException) { status = ((HttpServerErrorException) exception).getStatusCode(); } return new ResponseEntity<>(new ErrorResponse(error, "ServiceController"), status); } }
From source file:de.qucosa.webapi.v1.SearchResource.java
@RequestMapping(value = "/search", method = RequestMethod.GET) public ResponseEntity<String> search(@RequestParam Map<String, String> requestParameterMap) throws Exception { try {/* w ww . j a v a 2s.co m*/ Map<String, String> queries = new HashMap<>(); Map<String, String> orderby = new HashMap<>(); assertParametersPresent(requestParameterMap); extractQueriesAndSortParameters(requestParameterMap, queries, orderby); BoolQueryBuilder bqb = createBoolQueryBuilder(queries); SearchRequestBuilder searchRequestBuilder = elasticSearchClient.prepareSearch("fedora") .setTypes("object").setScroll(new TimeValue(60, TimeUnit.SECONDS)).setSize(100).setQuery(bqb) .addFields(searchFieldnameMap.get("docid"), searchFieldnameMap.get("title"), searchFieldnameMap.get("author"), searchFieldnameMap.get("completeddate"), searchFieldnameMap.get("doctype")); addSortParameter(orderby, searchRequestBuilder); log.debug("Issue query: " + searchRequestBuilder.toString()); SearchResponse searchResponse = searchRequestBuilder.execute().actionGet(); return scrollAndBuildResultList(searchResponse); } catch (ElasticsearchException esx) { log.error("ElasticSearch specific error: {}", esx.getMessage()); return errorResponse("Internal Server Error.", HttpStatus.INTERNAL_SERVER_ERROR); } catch (BadSearchRequestException bsr) { log.error("Bad search request: {}", bsr.getMessage()); return errorResponse(bsr.getMessage(), HttpStatus.BAD_REQUEST); } catch (Exception ex) { log.error("Unexpected Exception: {}", ex.getMessage()); return errorResponse("Internal Server Error.", HttpStatus.INTERNAL_SERVER_ERROR); } }