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.hp.autonomy.frontend.find.hod.search.FindHodDocumentServiceTest.java

@Test(expected = HodErrorException.class)
public void miscellaneousError() throws HodErrorException {
    final HodError miscellaneousError = new HodError.Builder().setErrorCode(HodErrorCode.UNKNOWN).build();
    when(queryTextIndexService.queryTextIndexWithText(anyString(), any(QueryRequestBuilder.class)))
            .thenThrow(new HodErrorException(miscellaneousError, HttpStatus.INTERNAL_SERVER_ERROR.value()));

    final QueryRestrictions<ResourceIdentifier> queryRestrictions = testUtils.buildQueryRestrictions();
    final SearchRequest<ResourceIdentifier> searchRequest = new SearchRequest.Builder<ResourceIdentifier>()
            .setQueryRestrictions(queryRestrictions).setStart(1).setMaxResults(30).setSummary("concept")
            .setSummaryCharacters(250).setSort(null).setHighlight(true).setAutoCorrect(false)
            .setQueryType(SearchRequest.QueryType.MODIFIED).build();
    documentsService.queryTextIndex(searchRequest);
}

From source file:jp.classmethod.aws.brian.web.TriggerController.java

/**
 * Delete specified triggerGroup (belonging triggers).
 * /*from w w w.j  ava 2s.  c om*/
 * @param triggerGroupName trigger group name
 * @return wherther the trigger is removed
 * @throws SchedulerException
 */
@ResponseBody
@RequestMapping(value = "/triggers/{triggerGroupName}/", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteTriggerGroup(@PathVariable("triggerGroupName") String triggerGroupName)
        throws SchedulerException {
    logger.info("deleteTriggerGroup {}", triggerGroupName);

    List<String> triggers = listTriggers(triggerGroupName);
    Set<String> failed = triggers.stream().filter(triggerName -> {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        try {
            return scheduler.unscheduleJob(triggerKey) == false;
        } catch (SchedulerException e) {
            logger.error("unexpected", e);
        }
        return false;
    }).collect(Collectors.toSet());

    if (failed.isEmpty()) {
        return ResponseEntity.ok(triggers);
    }
    Map<String, Object> map = new HashMap<>();
    map.put("failed", failed);
    map.put("deleted", triggers.stream().filter(t -> failed.contains(t) == false).collect(Collectors.toList()));
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new BrianResponse<>(false, "failed to unschedule", map));
}

From source file:com.javafxpert.wikibrowser.util.WikidataLoader.java

@RequestMapping(value = "/wikidataload", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity<Object> loadWikidata(@RequestParam(value = "onesdigit") String onesDigit,
        @RequestParam(value = "startnum", defaultValue = "1") String startNum,
        @RequestParam(value = "process", defaultValue = "items") String processType,
        @RequestParam(value = "lang", defaultValue = "en") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);
    String status = "OK";
    String userDir = System.getProperty("user.dir");

    log.info("WikidataLoader starting, onesDigit=" + onesDigit + ", startNum: " + startNum + ", userDir: "
            + userDir);// w  ww .  j a v a 2 s. c  o m

    int onesDigitInt = 0;
    int startNumInt = 0;
    try {
        onesDigit = onesDigit.trim();
        onesDigitInt = Integer.parseInt(onesDigit);
        startNum = startNum.trim();
        startNumInt = Integer.parseInt(startNum);
        if (userDir.equals("/Users/jamesweaver/wikidata-stuff/wikidata-loader")) {
            //if (userDir.equals("/Users/jamesweaver/spring-guides/wikibrowser-service")) {
            log.info("********* Will begin processing, onesDigit=" + onesDigit + ", onesDigitInt ="
                    + onesDigitInt + ", startNumInt =" + startNumInt + ", processType =" + processType
                    + "**********");
            WikidataNeo4jProcessor wikidataNeo4jProcessor = new WikidataNeo4jProcessor(itemRepository, language,
                    onesDigitInt, startNumInt, processType);
            ExampleHelpers.processEntitiesFromWikidataDump(wikidataNeo4jProcessor);
        } else {
            status = "Criteria for running not satisfied";
            log.info(status);
        }
    } catch (NumberFormatException nfe) {
        log.info("Invalid onesdigit, must be 0-9");
    }

    return Optional.ofNullable(status) //TODO: Replace with indicator of how it went
            .map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikidata load unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));

}

From source file:de.pentasys.playground.springbootexample.SampleActuatorApplicationTests.java

@Test
public void testErrorPage() throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate("admin", getPassword())
            .getForEntity("http://localhost:" + this.port + "/foo", String.class);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
    String body = entity.getBody();
    assertNotNull(body);/*from  w w  w. ja v a  2s  .  c o  m*/
    assertTrue("Wrong body: " + body, body.contains("Internal Server Error"));
}

From source file:com.impetus.ankush.common.utils.UploadHandler.java

/**
 * Upload file.//from ww  w .j  a va 2s  .c  o m
 * 
 * @return the string
 */
public String uploadFile() {

    if (multipartFile == null) {
        throw new ControllerException(HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST.toString(),
                "No payload with name \"file\" found in the request ");
    }

    // file path to upload.
    String realFilePath = null;
    try {
        // getting original file name.
        String originalFileName = multipartFile.getOriginalFilename();

        // making real file path.
        realFilePath = this.getUploadFolderPath() + originalFileName;

        // destination file.
        File dest = new File(realFilePath);

        multipartFile.transferTo(dest);
    } catch (IllegalStateException e) {
        throw new ControllerException(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage());
    } catch (IOException e) {
        throw new ControllerException(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.INTERNAL_SERVER_ERROR.toString(), e.getMessage());
    }
    return realFilePath;
}

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

@RequestMapping(produces = "application/json", method = RequestMethod.POST)
public ResponseEntity respondToEvent(@RequestParam(value = "response") String responseString,
        @RequestParam(value = "id") String eventID, @CurrentUser User currentUser) {
    logger.debug("[{}] Responding to event {} with {}", currentUser, eventID, responseString);
    Event event;/*from  w w w  .  ja  v  a  2s  . c om*/
    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());
            if (response == EventStatus.REMOVED || response == EventStatus.PENDING) {
                logger.warn("[{}] Unable to select 'removed' or 'pending' as a response for an event");
                return new ResponseEntity(HttpStatus.BAD_REQUEST);
            }
        } 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 {
            event.getInvitedUser().put(currentUser.getId(), response);
            eventRepository.save(event);
            logger.info("[{}] Successfully responded to event {} with response {}", currentUser, event,
                    response);
            return new ResponseEntity(HttpStatus.OK);
        }
    }
}

From source file:com.crazyacking.learn.spring.actuator.SampleActuatorApplicationTests.java

@Test
public void testErrorPage() {
    ResponseEntity<String> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/foo",
            String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
    String body = entity.getBody();
    assertThat(body).contains("\"error\":");
}

From source file:org.osiam.addons.selfadministration.controller.LostPasswordController.java

/**
 * This endpoint generates an one time password and send an confirmation email including the one time password to
 * users primary email//  w w w  . j a  v  a2 s .c o  m
 * 
 * @param authorization
 *        authZ header with valid access token
 * @param userId
 *        the user id for whom you want to change the password
 * @return the HTTP status code
 * @throws IOException
 * @throws MessagingException
 */
@RequestMapping(value = "/lost/{userId}", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> lost(@RequestHeader("Authorization") final String authorization,
        @PathVariable final String userId) throws IOException, MessagingException {

    // generate one time password
    String newOneTimePassword = UUID.randomUUID().toString();
    UpdateUser updateUser = getPreparedUserForLostPassword(newOneTimePassword);

    User updatedUser;
    try {
        String token = RegistrationHelper.extractAccessToken(authorization);
        AccessToken accessToken = new AccessToken.Builder(token).build();
        updatedUser = connectorBuilder.createConnector().updateUser(userId, updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.log(Level.WARNING, e.getMessage());
        return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    Optional<Email> email = SCIMHelper.getPrimaryOrFirstEmail(updatedUser);
    if (!email.isPresent()) {
        String errorMessage = "Could not change password. No email of user " + updatedUser.getUserName()
                + " found!";
        LOGGER.log(Level.WARNING, errorMessage);
        return getErrorResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
    }

    String passwordLostLink = RegistrationHelper.createLinkForEmail(passwordlostLinkPrefix, updatedUser.getId(),
            "oneTimePassword", newOneTimePassword);

    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("lostpasswordlink", passwordLostLink);
    mailVariables.put("user", updatedUser);

    Locale locale = RegistrationHelper.getLocale(updatedUser.getLocale());

    try {
        renderAndSendEmailService.renderAndSendEmail("lostpassword", fromAddress, email.get().getValue(),
                locale, mailVariables);
    } catch (OsiamException e) {
        return getErrorResponseEntity("Problems creating email for lost password: \"" + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

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

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

/**
 * Creates a new User/*  w  w  w  .j  av a 2  s . c  om*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
@PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<User> createUser(HttpServletRequest request, @PathVariable String orgMrn,
        @Valid @RequestBody User 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());
        }
        // If the organization doesn't have its own Identity Provider we create the user in a special keycloak instance
        if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null
                || org.getIdentityProviderAttributes().isEmpty())) {
            String password = PasswordUtil.generatePassword();
            keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE);
            try {
                keycloakAU.createUser(input.getMrn(), password, input.getFirstName(), input.getLastName(),
                        input.getEmail(), orgMrn, input.getPermissions(), true);
            } catch (DuplicatedKeycloakEntry dke) {
                throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(),
                        request.getServletPath());
            } catch (IOException e) {
                throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                        MCIdRegConstants.ERROR_CREATING_KC_USER, request.getServletPath());
            }
            // Send email to user with credentials
            emailUtil.sendUserCreatedEmail(input.getEmail(), input.getFirstName() + " " + input.getLastName(),
                    input.getEmail(), password);
        }
        input.setIdOrganization(org.getId());
        try {
            User newUser = this.entityService.save(input);
            return new ResponseEntity<>(newUser, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            // If save to DB failed, remove the user from keycloak if it was created.
            if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null
                    || org.getIdentityProviderAttributes().isEmpty())) {
                keycloakAU.deleteUser(input.getEmail());
            }
            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:io.jmnarloch.spring.boot.rxjava.async.ObservableDeferredResultTest.java

@Test
public void shouldTimeoutOnConnection() {

    // when//from  w  w  w  .  j a v  a2s  .c o  m
    ResponseEntity<Object> response = restTemplate.getForEntity(path("/timeout"), Object.class);

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