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.haulmont.idp.controllers.IdpController.java

@GetMapping(value = "/logout")
public String logout(@RequestParam(value = "sp", defaultValue = "") String serviceProviderUrl,
        @RequestParam(value = "response_type", defaultValue = "server-ticket") String responseType,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {//from  w w w.  j a  va  2 s.  com
    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    // remove auth cookie
    Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
    cookie.setMaxAge(0);
    response.addCookie(cookie);

    if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
        return "redirect:login.html" + "?response_type=" + ResponseType.CLIENT_TICKET.getCode() + "&sp="
                + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
    }

    return "redirect:login.html?sp=" + URLEncodeUtils.encodeUtf8(serviceProviderUrl);
}

From source file:comsat.sample.actuator.SampleActuatorApplicationTests.java

private void testErrorPage(final String path) throws Exception {
    ResponseEntity<String> entity = new TestRestTemplate("user", getPassword())
            .getForEntity("http://localhost:" + this.port + "/" + emptyIfNull(path) + "/foo", String.class);
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, entity.getStatusCode());
    String body = entity.getBody();
    assertNotNull(body);//  w w w  . ja v  a2  s .com
    assertTrue("Wrong body: " + body, body.contains("\"error\":"));
}

From source file:org.dawnsci.marketplace.controllers.ExtendedRestApiController.java

/**
 * Uploads a screenshot to the solution and updates the solution data with
 * the name of the file being uploaded. Returns a <b>403 Forbidden</b> if
 * the logged in user is not the owner of the solution.
 *///from w ww .  jav a 2s .  c  o  m
@PreAuthorize("hasRole('UPLOAD')")
@RequestMapping(value = "/upload-screenshot")
public ResponseEntity<String> uploadScreenshot(Principal principal, @RequestParam("id") Long id,
        @RequestParam("file") MultipartFile file) throws Exception {
    // verify that we have the correct owner
    Account account = accountRepository.findOne(principal.getName());
    if (!canEdit(principal, id)) {
        return new ResponseEntity<String>("Logged in user is not the owner of the solution",
                HttpStatus.FORBIDDEN);
    }
    fileService.saveSolutionFile(id, file);
    // get solution and update with new information
    Node node = marketplaceDAO.getSolution(id);
    node.setScreenshot(file.getOriginalFilename());
    Object result = marketplaceDAO.saveOrUpdateSolution(node, account);
    if (result instanceof Node) {
        return new ResponseEntity<String>(MarketplaceSerializer.serialize((Node) result), HttpStatus.OK);
    } else {
        return new ResponseEntity<String>((String) result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

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

/**
 * Saving the new E-Mail temporary, generating confirmation token and sending an E-Mail to the old registered
 * address./*from ww  w . j a v a 2s.c  o m*/
 * 
 * @param authorization
 *        Authorization header with HTTP Bearer authorization and a valid access token
 * @param newEmailValue
 *        The new email address value
 * @return The HTTP status code
 * @throws IOException
 * @throws MessagingException
 */
@RequestMapping(method = RequestMethod.POST, value = "/change", produces = "application/json")
public ResponseEntity<String> change(@RequestHeader("Authorization") final String authorization,
        @RequestParam("newEmailValue") final String newEmailValue) throws IOException, MessagingException {

    User updatedUser;
    String confirmationToken = UUID.randomUUID().toString();
    try {
        updatedUser = getUpdatedUserForEmailChange(RegistrationHelper.extractAccessToken(authorization),
                newEmailValue, confirmationToken);
    } 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);
    }

    String activateLink = RegistrationHelper.createLinkForEmail(emailChangeLinkPrefix, updatedUser.getId(),
            "confirmToken", confirmationToken);

    // build the Map with the link for replacement
    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("activatelink", activateLink);
    mailVariables.put("user", updatedUser);

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

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemail", fromAddress, newEmailValue, locale,
                mailVariables);
    } catch (OsiamException e) {
        return getErrorResponseEntity(
                "Problems creating email for confirming new user email: \"" + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.trustedanalytics.user.invite.rest.InvitationsController.java

@ExceptionHandler(InvitationNotSentException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected ErrorDescriptionModel invitationNotSend(InvitationNotSentException e) {
    return new ErrorDescriptionModel(ErrorDescriptionModel.State.ERROR, e.getInvContent());
}

From source file:org.craftercms.profile.controllers.rest.ExceptionHandlers.java

@ExceptionHandler(PermissionException.class)
public ResponseEntity<Object> handlePermissionException(PermissionException e, WebRequest request) {
    return handleExceptionInternal(e, HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.PERMISSION_ERROR, request);
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.restapi.PublisherController.java

@ExceptionHandler({ EngineBuildingException.class, EnginePublicationException.class })
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody//from  www .j a v  a  2 s.  c  om
public String handleEngineBuildingException(Exception e) {
    LOGGER.error("Problem while building/publishing scoring engine: ", e);
    return e.getMessage();
}

From source file:org.n52.tamis.rest.controller.processes.ExecuteProcessController.java

/**
 * Returns the shortened single process description.
 * // w  ww  .j  ava  2 s .c o m
 * @param serviceID
 *            inside the URL the variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} specifies
 *            the id of the service. * @param request
 * @param processId
 *            inside the URL the variable
 *            {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} specifies
 *            the id of the process.
 * @param request
 * @return the shortened single process description
 */
@RequestMapping("")
public ResponseEntity executeProcess(@RequestBody Execute_HttpPostBody requestBody,
        @RequestParam(value = SYNC_EXECUTE_PARAMETER_NAME, required = false, defaultValue = "false") boolean sync_execute,
        @PathVariable(URL_Constants_TAMIS.SERVICE_ID_VARIABLE_NAME) String serviceId,
        @PathVariable(URL_Constants_TAMIS.PROCESS_ID_VARIABLE_NAME) String processId,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.info(
            "Received execute process request for service id \"{}\" and process id \"{}\"! URL request parameter \"{}\" is of value \"{}\".",
            serviceId, processId, SYNC_EXECUTE_PARAMETER_NAME, sync_execute);

    /*
     * in the following we add an attribute to the request which is used
     * later by ExecuteReqeustForwarder.java to create proper URL of WPS
     * proxy.
     * 
     * This is necessary, since the URL parameter "sync-execute" is
     * optional, and thus, might not exist. Hence, we add the attribute
     * manually, which is afterwards guaranteed to be present.
     */
    if (sync_execute) {
        request.setAttribute(SYNC_EXECUTE_PARAMETER_NAME, true);
    } else {
        request.setAttribute(SYNC_EXECUTE_PARAMETER_NAME, false);
    }
    /*
     * else: syncExecute is set to "false" per default.
     */

    parameterValueStore.addParameterValuePair(URL_Constants_TAMIS.SERVICE_ID_VARIABLE_NAME, serviceId);
    parameterValueStore.addParameterValuePair(URL_Constants_TAMIS.PROCESS_ID_VARIABLE_NAME, processId);

    /*
     * execute response may either be a String (= the location header of an
     * asynchronously executed job) or an instance of ResultDocument (in
     * case of synchronous job execution)
     * 
     * Hence, we have to consider both cases!
     */
    Object executeResponse = executeRequestForwarder.forwardRequestToWpsProxy(request, requestBody,
            parameterValueStore);

    if (executeResponse instanceof String) {
        /* 
         * response of asynchronous job execution. 
         * 
         * Thus set location header
         */
        String locationHeaer = (String) executeResponse;
        response.setHeader("Location", locationHeaer);

        return new ResponseEntity(HttpStatus.CREATED);
    } else if (executeResponse instanceof ResultDocument) {
        /*
         * response of synchronous job execution.
         * 
         * simply return the resultDocument.
         */
        ResultDocument resultDoc = (ResultDocument) executeResponse;

        return ResponseEntity.ok(resultDoc);
    } else {
        logger.error(
                "The response of the execute request is of unexpected type. Either String (as location header from synchonous job execution) or ResultDocument (for asynchronous job execution) were expected. Response is of type {}!",
                executeResponse.getClass());

        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

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

@Test
public void testErrorPageDirectAccess() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = this.restTemplate.withBasicAuth("user", getPassword()).getForEntity("/error",
            Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
    @SuppressWarnings("unchecked")
    Map<String, Object> body = entity.getBody();
    assertThat(body.get("error")).isEqualTo("None");
    assertThat(body.get("status")).isEqualTo(999);
}

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

/**
 * Lists all available tasks./*from  w ww  .j a  v a2  s.  c  om*/
 *
 * @return array of task informations
 */
@RequestMapping(value = "/rest/harvester/tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TaskResponse[]> listTasks() {
    try {
        LOG.debug(String.format("GET /rest/harvester/tasks"));
        return new ResponseEntity<>(engine.getTasksService().selectTaskDefinitions(null).stream()
                .map(d -> new TaskResponse(d.getKey(), d.getValue())).collect(Collectors.toList())
                .toArray(new TaskResponse[0]), HttpStatus.OK);
    } catch (DataProcessorException ex) {
        LOG.error(String.format("Error listing tasks."), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}