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:br.com.modoagil.asr.rest.support.RESTErrorHandler.java
/** * Manipula excees para status HTTP {@code 500} * * @param ex/*from w ww . j a v a 2s. co m*/ * {@link Exception} * @return resposta ao cliente */ @ResponseBody @ExceptionHandler({ ConversionNotSupportedException.class, HttpMessageNotWritableException.class }) public Response<E> processInternalServerErrors(final Exception ex) { this.logger.info("handle" + ex.getClass().getName() + " - Catching: " + ex.getClass().getSimpleName(), ex); return new ResponseBuilder<E>().success(false).message(ex.getMessage()) .status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
From source file:org.kew.rmf.reconciliation.ws.ReconciliationServiceController.java
/** * Single reconciliation query./* w ww.j a v a 2 s. c o m*/ */ @RequestMapping(value = "/reconcile/{configName}", method = { RequestMethod.GET, RequestMethod.POST }, params = { "query", "callback" }, produces = "application/json; charset=UTF-8") public ResponseEntity<String> doSingleQuery(@PathVariable String configName, @RequestParam("query") String query, @RequestParam(value = "callback", required = false) String callback) { logger.info("{}: Single query request {}", configName, query); String jsonres = null; try { Query q = jsonMapper.readValue(query, Query.class); QueryResult[] qres = doQuery(q, configName); QueryResponse<QueryResult> response = new QueryResponse<>(); response.setResult(qres); jsonres = jsonMapper.writeValueAsString(response); } catch (JsonMappingException | JsonGenerationException e) { logger.warn(configName + ": Error parsing JSON query", e); return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (IOException e) { return new ResponseEntity<String>(e.toString(), HttpStatus.INTERNAL_SERVER_ERROR); } catch (MatchExecutionException e) { return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND); } catch (TooManyMatchesException e) { return new ResponseEntity<String>(e.toString(), HttpStatus.CONFLICT); } return new ResponseEntity<String>(wrapResponse(callback, jsonres), HttpStatus.OK); }
From source file:com.orange.cepheus.cep.controller.AdminController.java
@ExceptionHandler(PersistenceException.class) public ResponseEntity<StatusCode> persistenceExceptionHandler(HttpServletRequest req, PersistenceException exception) { logger.error("Persistance error", exception); StatusCode statusCode = new StatusCode(); statusCode.setCode("500"); statusCode.setReasonPhrase(exception.getMessage()); if (exception.getCause() != null) { statusCode.setDetail(exception.getCause().getMessage()); }/*from ww w.jav a 2s .c o m*/ return new ResponseEntity<>(statusCode, HttpStatus.INTERNAL_SERVER_ERROR); }
From source file:com.esri.geoportal.harvester.rest.BrokerController.java
/** * Adds a new task./*from ww w. ja v a 2 s . c o m*/ * @param brokerDefinition broker definition * @param brokerId broker id * @return broker info of the task which has been replaced */ @RequestMapping(value = "/rest/harvester/brokers/{brokerId}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<BrokerResponse> updateBroker(@RequestBody EntityDefinition brokerDefinition, @PathVariable UUID brokerId) { try { LOG.debug(formatForLog("PUT /rest/harvester/brokers/%s <-- %s", brokerId, brokerDefinition)); return new ResponseEntity<>(BrokerResponse.createFrom(engine.getBrokersService().updateBroker(brokerId, brokerDefinition, LocaleContextHolder.getLocale())), HttpStatus.OK); } catch (DataProcessorException ex) { LOG.error(formatForLog("Error updating broker: %s <-- %s", brokerId, brokerDefinition), ex); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
From source file:cn.org.once.cstack.config.RestHandlerException.java
@ExceptionHandler(value = { IndexOutOfBoundsException.class }) protected ResponseEntity<Object> handleIndexOutOfBoundsException(Exception ex, WebRequest request) { ex.printStackTrace();//ww w .j a v a 2 s. c o m HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(ex, new HttpErrorServer("An unkown error has occured! Server response : IndexOutOfBoundsException"), headers, HttpStatus.INTERNAL_SERVER_ERROR, request); }
From source file:com.frequentis.maritime.mcsr.web.rest.AccountResource.java
/** * POST /account : update the current user information. * * @param userDTO the current user information * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated *///from w ww .j av a2 s . com @RequestMapping(value = "/account", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<String> saveAccount(@Valid @RequestBody UserDTO userDTO) { Optional<User> existingUser = userRepository.findFirstByEmail(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")) .body(null); } return userRepository.findFirstByLogin(SecurityUtils.getCurrentUserLogin()).map(u -> { userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()); return new ResponseEntity<String>(HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); }
From source file:org.mitre.openid.connect.web.ProtectedResourceRegistrationEndpoint.java
/** * Create a new Client, issue a client ID, and create a registration access token. * @param jsonString/*from w ww . j ava2s . c o m*/ * @param m * @param p * @return */ @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public String registerNewProtectedResource(@RequestBody String jsonString, Model m) { ClientDetailsEntity newClient = null; try { newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); } catch (JsonSyntaxException e) { // bad parse // didn't parse, this is a bad request logger.error("registerNewProtectedResource failed; submitted JSON is malformed"); m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 return HttpCodeView.VIEWNAME; } if (newClient != null) { // it parsed! // // Now do some post-processing consistency checks on it // // clear out any spurious id/secret (clients don't get to pick) newClient.setClientId(null); newClient.setClientSecret(null); // do validation on the fields try { newClient = validateScopes(newClient); newClient = validateAuth(newClient); } catch (ValidationException ve) { // validation failed, return an error m.addAttribute(JsonErrorView.ERROR, ve.getError()); m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription()); m.addAttribute(HttpCodeView.CODE, ve.getStatus()); return JsonErrorView.VIEWNAME; } // no grant types are allowed newClient.setGrantTypes(new HashSet<String>()); newClient.setResponseTypes(new HashSet<String>()); newClient.setRedirectUris(new HashSet<String>()); // don't issue tokens to this client newClient.setAccessTokenValiditySeconds(0); newClient.setIdTokenValiditySeconds(0); newClient.setRefreshTokenValiditySeconds(0); // clear out unused fields newClient.setDefaultACRvalues(new HashSet<String>()); newClient.setDefaultMaxAge(null); newClient.setIdTokenEncryptedResponseAlg(null); newClient.setIdTokenEncryptedResponseEnc(null); newClient.setIdTokenSignedResponseAlg(null); newClient.setInitiateLoginUri(null); newClient.setPostLogoutRedirectUris(null); newClient.setRequestObjectSigningAlg(null); newClient.setRequireAuthTime(null); newClient.setReuseRefreshToken(false); newClient.setSectorIdentifierUri(null); newClient.setSubjectType(null); newClient.setUserInfoEncryptedResponseAlg(null); newClient.setUserInfoEncryptedResponseEnc(null); newClient.setUserInfoSignedResponseAlg(null); // this client has been dynamically registered (obviously) newClient.setDynamicallyRegistered(true); // this client has access to the introspection endpoint newClient.setAllowIntrospection(true); // now save it try { ClientDetailsEntity savedClient = clientService.saveNewClient(newClient); // generate the registration access token OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient); tokenService.saveAccessToken(token); // send it all out to the view RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); m.addAttribute("client", registered); m.addAttribute(HttpCodeView.CODE, HttpStatus.CREATED); // http 201 return ClientInformationResponseView.VIEWNAME; } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); m.addAttribute(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR); return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata"); m.addAttribute(JsonErrorView.ERROR_MESSAGE, "Unable to save client due to invalid or inconsistent metadata."); m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 return JsonErrorView.VIEWNAME; } } else { // didn't parse, this is a bad request logger.error("registerNewClient failed; submitted JSON is malformed"); m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 return HttpCodeView.VIEWNAME; } }
From source file:com.github.ukase.web.UkaseController.java
@ExceptionHandler(InterruptedException.class) @ResponseBody//ww w . ja va 2s. co m public ResponseEntity<ExceptionMessage> handleInterruptedException(InterruptedException e) { HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; ExceptionMessage message = new ExceptionMessage(e.getMessage(), status.value()); log.warn("Interrupted: {}", message); return new ResponseEntity<>(message, status); }
From source file:de.steilerdev.myVerein.server.controller.admin.SettingsController.java
/** * This function is saving the settings for the system durable. In case the database connection changed, the system is restarted. The function is invoked by POSTing the parameters to the URI /api/admin/settings. * NOTE: At the moment the restarting of the application is not working correctly. To apply changed database settings the application needs to be redeployed manually from the management interface. * @param currentAdmin If the logged in user is a super admin, this field specifies the new super admin. If the logged in user is a normal admin, this field needs to contain his email. * @param adminPasswordNew The new password for the currently logged in admin. * @param adminPasswordNewRe The retyped new password for the currently logged in admin. * @param clubName The club name./*from w w w. ja va2 s . co m*/ * @param clubLogo The club logo. If this parameter is present the former club logo is going to be replaced. * @param databaseHost The hostname of the used MongoDB server. * @param databasePort The port of the used MongoDB server. * @param databaseUser The username, used to authenticate against the MongoDB server. * @param databasePassword The password, used to authenticate against the MongoDB server. * @param databaseCollection The name of the database collection, where the data of this system is stored in. * @param rememberMeTokenKey The phrase used to secure the remember me cookies. * @param parameters The complete map of all parameters, containing the custom user fields. * @param currentAdminPassword The password of the currently logged in user, used to authenticate the changes. * @param currentUser The currently logged in 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. */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<String> saveSettings(@RequestParam(required = false) String currentAdmin, @RequestParam(required = false) String adminPasswordNew, @RequestParam(required = false) String adminPasswordNewRe, @RequestParam(required = false) String clubName, @RequestParam(required = false) MultipartFile clubLogo, @RequestParam(required = false) String databaseHost, @RequestParam(required = false) String databasePort, @RequestParam(required = false) String databaseUser, @RequestParam(required = false) String databasePassword, @RequestParam(required = false) String databaseCollection, @RequestParam Map<String, String> parameters, @RequestParam String currentAdminPassword, @CurrentUser User currentUser) { logger.trace("[" + currentUser + "] Starting to save settings"); Settings settings = Settings.loadSettings(settingsRepository); if (!passwordEncoder.isPasswordValid(currentUser.getPassword(), currentAdminPassword, currentUser.getSalt())) { logger.warn("[" + currentUser + "] The stated password is invalid"); return new ResponseEntity<>("The stated password is incorrect, please try again", HttpStatus.FORBIDDEN); } else if (currentUser.isAdmin()) { if (currentUser.isSuperAdmin()) { logger.debug("[" + currentUser + "] The user is a super admin"); if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) { logger.warn("[" + currentUser + "] The super admin user is changing to " + currentAdmin); Division rootDivision = divisionRepository.findByName(settings.getClubName()); if (rootDivision == null) { logger.warn("[" + currentUser + "] Unable to find root division " + settings.getClubName()); return new ResponseEntity<>("Unable to find root division", HttpStatus.INTERNAL_SERVER_ERROR); } User newSuperAdmin = userRepository.findByEmail(currentAdmin); if (newSuperAdmin == null) { logger.warn("[" + currentUser + "] Unable to find new super admin " + currentAdmin); return new ResponseEntity<>("Unable to find new super admin", HttpStatus.INTERNAL_SERVER_ERROR); } logger.debug("[" + currentUser + "] Saving new super admin"); rootDivision.setAdminUser(newSuperAdmin); divisionRepository.save(rootDivision); logger.info("[" + currentUser + "] Successfully saved " + currentAdmin + " as new super admin"); } try { if (clubName != null && !clubName.isEmpty()) { logger.debug("[" + currentUser + "] Setting club name to " + clubName); Division rootDivision = divisionRepository.findByName(settings.getClubName()); if (rootDivision == null) { logger.warn("[" + currentUser + "] Unable to find former root division."); return new ResponseEntity<>("Unable to find former root division", HttpStatus.INTERNAL_SERVER_ERROR); } //Changing and saving the root division rootDivision.setName(clubName); divisionRepository.save(rootDivision); settings.setClubName(clubName); } if (clubLogo != null && !clubLogo.isEmpty()) { logger.debug("[" + currentUser + "] Saving club logo"); try { gridFSRepository.storeClubLogo(clubLogo); } catch (MongoException e) { logger.warn("[" + currentUser + "] Problem while saving club logo: " + e.getMessage()); return new ResponseEntity<>("Problem while saving club logo: " + e.getMessage(), HttpStatus.BAD_REQUEST); } } if (databaseHost != null && !databaseHost.isEmpty()) { logger.debug("[" + currentUser + "] Setting database host to " + databaseHost); settings.setDatabaseHost(databaseHost); } if (databasePort != null && !databasePort.isEmpty()) { logger.debug("[" + currentUser + "] Setting database port to " + databasePort); settings.setDatabasePort(databasePort); } if (databaseUser != null) { logger.debug("[" + currentUser + "] Setting database user to " + databaseUser); settings.setDatabaseUser(databaseUser); } if (databasePassword != null) { logger.debug("[" + currentUser + "] Setting database password"); settings.setDatabasePassword(databasePassword); } if (databaseCollection != null && !databaseCollection.isEmpty()) { logger.debug( "[" + currentUser + "] Setting database collection name " + databaseCollection); settings.setDatabaseName(databaseCollection); } logger.debug("[" + currentUser + "] Gathering all custom user fields"); //Reducing parameters to custom user field parameters only and the value of the input List<String> reducedValues = parameters.keySet().parallelStream() .filter(key -> key.startsWith("cuf_") && !parameters.get(key).trim().isEmpty()) .distinct() //Only allowing distinct keys .map(key -> key.substring(4)) //Reducing the key to the initial 'name' value, used to create the fields by jQuery .collect(Collectors.toList()); //Analysing the values and checking, if if (!reducedValues.isEmpty()) { logger.debug("[" + currentUser + "] There are custom user fields available"); ArrayList<String> customUserFieldValues = new ArrayList<>(); reducedValues.parallelStream().forEach(key -> { if (parameters.get("delete" + key) != null) { logger.warn("[" + currentUser + "] Deleting custom user field " + key); if (parameters.get("deleteContent" + key) != null) { logger.warn("[" + currentUser + "] Deleting content of custom user field " + key + " on every user object"); List<User> user = mongoTemplate.find( new Query(Criteria.where("customUserField." + key).exists(true)), User.class); if (user != null && !user.isEmpty()) { user.parallelStream().forEach(thisUser -> { thisUser.removeCustomUserField(key); try { logger.trace( "[" + currentUser + "] Deleting custom user field content " + key + " for user " + thisUser.getEmail()); userRepository.save(thisUser); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while trying to delete the custom user field " + key + " for user " + thisUser.getEmail() + ": " + e.getMessage()); } }); } } } else { String value = parameters.get("cuf_" + key).trim(); if (!key.equals(value) && settings.getCustomUserFields().contains(key)) //The key was renamed { logger.debug("[" + currentUser + "] The custom user field " + key + " changed to " + value); List<User> user = mongoTemplate.find( new Query(Criteria.where("customUserField." + key).exists(true)), User.class); if (user != null && !user.isEmpty()) { user.parallelStream().forEach(thisUser -> { thisUser.renameCustomUserField(key, value); try { logger.trace("[" + currentUser + "] Renaming custom user field " + key + " to " + value + " for user " + thisUser.getEmail()); userRepository.save(thisUser); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while trying to rename the custom user field " + key + " for user " + thisUser.getEmail() + ": " + e.getMessage()); } }); } } logger.debug("[" + currentUser + "] Adding " + value + " as custom user field"); customUserFieldValues.add(value); } }); settings.setCustomUserFields(customUserFieldValues); } logger.debug("[" + currentUser + "] Saving updated settings file"); settings.saveSettings(currentUser, settingsRepository); logger.info("[" + currentUser + "] Successfully saved updated settings file"); } catch (IOException e) { logger.warn("[" + currentUser + "] Unable to update settings file: " + e.getMessage()); return new ResponseEntity<>("Unable to update settings file", HttpStatus.INTERNAL_SERVER_ERROR); } } else { logger.debug("[" + currentUser + "] The user is an admin"); if (currentAdmin != null && !currentAdmin.equals(currentUser.getEmail())) { logger.warn("[" + currentUser + "] The current user differs from the stated user"); return new ResponseEntity<>("The current user differs from the stated user", HttpStatus.BAD_REQUEST); } } if (adminPasswordNew != null && adminPasswordNewRe != null && !adminPasswordNew.isEmpty() && !adminPasswordNewRe.isEmpty()) { logger.info("[" + currentUser + "] The user wants to change his password."); if (!adminPasswordNew.equals(adminPasswordNewRe)) { logger.warn("[" + currentUser + "] The stated passwords did not match"); return new ResponseEntity<>("The stated passwords did not match", HttpStatus.BAD_REQUEST); } else { currentUser.setPassword(adminPasswordNew); try { logger.debug("[" + currentUser + "] Saving new user password."); userRepository.save(currentUser); logger.info("[" + currentUser + "] Successfully saved new user password"); } catch (ConstraintViolationException e) { logger.warn("[" + currentUser + "] A database constraint was violated while saving the user: " + e.getMessage()); return new ResponseEntity<>("A database constraint was violated while saving the user.", HttpStatus.BAD_REQUEST); } } } } else { logger.warn("[" + currentUser + "] A user who is not an admin tries to change the settings "); return new ResponseEntity<>("You are not allowed to change these settings", HttpStatus.FORBIDDEN); } logger.info("[" + currentUser + "] Successfully updated all settings"); return new ResponseEntity<>("Successfully updated settings", HttpStatus.OK); }
From source file:com.springsource.greenhouse.WebOAuthActivity.java
@UiThread void greenhousePostConnectFailed(Exception exception) { dismissProgressDialog();/*from w w w.j av a2s .c om*/ if (exception instanceof HttpClientErrorException) { if (((HttpServerErrorException) exception).getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) { displayAppAuthorizationError( "You are already connected with another Android device. Please remove the connection at Greenhouse and try again."); } } }