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.alexshabanov.springrestapi.ControllerMockTest.java

@Test
public void shouldGetInternalServerError() throws IOException {
    doThrow(UnsupportedOperationException.class).when(profileController).deleteProfile(id);
    when(profileController.handleUnsupportedOperationException()).thenReturn(errorDesc);

    try {//  ww w .ja  v a  2s.  com
        restClient.delete(path(CONCRETE_PROFILE_RESOURCE), id);
        fail();
    } catch (HttpServerErrorException e) {
        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, e.getStatusCode());
        final ErrorDesc actual = getObjectMapper().reader(ErrorDesc.class)
                .readValue(e.getResponseBodyAsString());
        assertEquals(errorDesc, actual);
    }
}

From source file:org.coursera.cmbrehm.kewlvideo.server.VideoController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.POST)
public ResponseEntity<VideoStatus> saveVideoData(@PathVariable("id") long id,
        @RequestPart("data") MultipartFile videoData) {
    ResponseEntity<VideoStatus> response;
    try {// ww w  .j av a 2s  .  co  m
        InputStream videoDataStream = videoData.getInputStream();
        VideoFileManager vfmgr = VideoFileManager.get();
        Video video = videoList.get(id);
        if (video != null) {
            vfmgr.saveVideoData(video, videoDataStream);
            response = new ResponseEntity<VideoStatus>(new VideoStatus(VideoState.READY), HttpStatus.ACCEPTED);
        } else {
            response = new ResponseEntity<VideoStatus>(HttpStatus.NOT_FOUND);
        }
    } catch (IOException iox) {
        response = new ResponseEntity<VideoStatus>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return response;
}

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

@RequestMapping(method = RequestMethod.POST, consumes = "application/json; charset=utf-8")
@PreAuthorize(value = "hasRole('AK_ADMIN')")
@ResponseStatus(HttpStatus.CREATED)//w  w w.java  2  s .  c  o m
public void collectionAdd(@Valid @RequestBody UserResource p, HttpServletRequest request,
        HttpServletResponse response) {

    User bo = dozerBeanMapper.map(p, User.class);
    bo.setIdUser(null);

    try {
        userRepo.save(bo);
    } catch (DataAccessException e) {
        logger.error("Can't create user into DB", e);
        throw new DefaultSportManagerException(
                new ErrorResource("db error", "Can't create user into DB", HttpStatus.INTERNAL_SERVER_ERROR));
    }

    response.setHeader("Location",
            request.getRequestURL().append((request.getRequestURL().toString().endsWith("/") ? "" : "/"))
                    .append(bo.getIdUser()).toString());

}

From source file:io.github.autsia.crowly.controllers.rest.CampaignsController.java

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ResponseEntity<String> delete(@RequestParam String campaignId, HttpServletResponse response) {
    try {//w  w w  . j a  v a 2s .c  o m
        Campaign campaign = campaignRepository.findOne(campaignId);
        campaignsManager.stopCampaign(campaign);
        campaignRepository.delete(campaignId);
        return new ResponseEntity<>(HttpStatus.OK);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.ow2.proactive.procci.rest.MixinRest.java

@RequestMapping(value = "{mixinTitle}", method = RequestMethod.DELETE)
public ResponseEntity<MixinRendering> removeMixin(@PathVariable("mixinTitle") String mixinTitle) {
    logger.debug("Deleting Mixin " + mixinTitle);

    Mixin mixin = null;/*  ww w  .  j a va  2s.co m*/
    try {
        mixin = mixinService.getMixinByTitle(mixinTitle);
        mixinService.removeMixin(mixinTitle);
    } catch (ServerException ex) {
        logger.error(this.getClass().getName(), ex);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (ClientException ex) {
        return new ResponseEntity(ex.getJsonError(), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity(mixin.getRendering(), HttpStatus.OK);
}

From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java

/**
 * Creates a new Service/*from www .  j  a  va 2s .  c om*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/service", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
@PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<Service> createService(HttpServletRequest request, @PathVariable String orgMrn,
        @Valid @RequestBody Service input, BindingResult bindingResult) throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being created belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        input.setIdOrganization(org.getId());
        // Setup a keycloak client for the service if needed
        if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) {
            // Check if the redirect uri is set if access type is "bearer-only"
            if (!"bearer-only".equals(input.getOidcAccessType())
                    && (input.getOidcRedirectUri() == null || input.getOidcRedirectUri().trim().isEmpty())) {
                throw new McBasicRestException(HttpStatus.BAD_REQUEST,
                        MCIdRegConstants.OIDC_MISSING_REDIRECT_URL, request.getServletPath());
            }
            keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE);
            input.setOidcClientId(input.getMrn());
            try {
                String clientSecret = keycloakAU.createClient(input.getMrn(), input.getOidcAccessType(),
                        input.getOidcRedirectUri());
                if ("confidential".equals(input.getOidcAccessType())) {
                    input.setOidcClientSecret(clientSecret);
                } else {
                    input.setOidcClientSecret(null);
                }
            } catch (IOException e) {
                throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                        MCIdRegConstants.ERROR_CREATING_KC_CLIENT, request.getServletPath());
            } catch (DuplicatedKeycloakEntry dke) {
                throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(),
                        request.getServletPath());
            }
        } else {
            input.setOidcAccessType(null);
            input.setOidcClientId(null);
            input.setOidcClientSecret(null);
            input.setOidcRedirectUri(null);
        }
        try {
            Service newService = this.entityService.save(input);
            return new ResponseEntity<>(newService, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            // If save to DB failed, remove the client from keycloak if it was created.
            if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) {
                keycloakAU.deleteClient(input.getMrn());
            }
            throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(),
                    request.getServletPath());
        }
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.jkratz.igdb.controller.advice.ErrorController.java

@RequestMapping(produces = "application/json")
@ExceptionHandler(DataAccessException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public @ResponseBody Map<String, Object> handleDataAccessException(DataAccessException ex) throws IOException {
    logger.error("Database Error", ex);
    Map<String, Object> map = Maps.newHashMap();
    map.put("error", "Data Error");
    map.put("message", ex.getMessage());
    if (ex.getRootCause() != null) {
        map.put("cause", ex.getRootCause().getMessage());
    }//  w ww  .  ja v a  2 s .  c  o m
    return map;
}

From source file:org.fineract.module.stellar.controller.BridgeController.java

@RequestMapping(value = "/trustlines/{assetCode}/{issuer}/", method = RequestMethod.PUT, consumes = {
        "application/json" }, produces = { "application/json" })
public ResponseEntity<Void> adjustTrustLine(@RequestHeader(API_KEY_HEADER_LABEL) final String apiKey,
        @RequestHeader(TENANT_ID_HEADER_LABEL) final String mifosTenantId,
        @PathVariable("assetCode") final String trustedAssetCode,
        @PathVariable("issuer") final String urlEncodedIssuingStellarAddress,
        @RequestBody final TrustLineConfiguration stellarTrustLineConfig)
        throws InvalidStellarAddressException {
    this.securityService.verifyApiKey(apiKey, mifosTenantId);

    final String issuingStellarAddress;
    try {//from  w ww. j a v a 2  s.  co m
        issuingStellarAddress = URLDecoder.decode(urlEncodedIssuingStellarAddress, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    this.bridgeService.adjustTrustLine(mifosTenantId, StellarAddress.parse(issuingStellarAddress),
            trustedAssetCode, stellarTrustLineConfig.getMaximumAmount());

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

From source file:io.jmnarloch.spring.boot.rxjava.async.ObservableDeferredResultTest.java

@Test
public void shouldRetrieveErrorResponse() {

    // when/*w ww.  j  a v  a 2 s . c  o  m*/
    ResponseEntity<Object> response = restTemplate.getForEntity(path("/throw"), Object.class);

    // then
    assertNotNull(response);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
}

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

@ExceptionHandler(value = { ClassCastException.class })
protected ResponseEntity<Object> handleClassCastException(Exception ex, WebRequest request) {
    ex.printStackTrace();/*  w w  w  .  ja  v  a 2  s .  c  om*/
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(ex,
            new HttpErrorServer("An unkown error has occured! Server response : ClassCastException"), headers,
            HttpStatus.INTERNAL_SERVER_ERROR, request);
}