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.sms.server.controller.AdminController.java

@RequestMapping(value = "/user/role", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody//from  w  w w  .  j  a v  a  2s. c o  m
public ResponseEntity<String> createUserRole(@RequestBody UserRole userRole) {
    // Check mandatory fields.
    if (userRole.getUsername() == null || userRole.getRole() == null) {
        return new ResponseEntity<>("Missing required parameter.", HttpStatus.BAD_REQUEST);
    }

    // Check unique fields
    if (userDao.getUserByUsername(userRole.getUsername()) == null) {
        return new ResponseEntity<>("Username is not registered.", HttpStatus.NOT_ACCEPTABLE);
    }

    // Add user role to the database.
    if (!userDao.createUserRole(userRole)) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME,
                "Error adding role'" + userRole.getRole() + "' to user '" + userRole.getUsername() + "'.",
                null);
        return new ResponseEntity<>("Error adding user role to database.", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME,
            "Added role'" + userRole.getRole() + "' to user '" + userRole.getUsername() + "'.", null);
    return new ResponseEntity<>("User role added successfully.", HttpStatus.CREATED);
}

From source file:it.reply.orchestrator.exception.GlobalControllerExceptionHandler.java

/**
 * Server Error exception handler./*from   w  w w  .j a  va 2 s  .co  m*/
 * 
 * @param ex
 *          the exception
 * @return a {@code ResponseEntity} instance
 */
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
Error handleException(Exception ex) {

    return new Error().withCode(HttpStatus.INTERNAL_SERVER_ERROR.value())
            .withTitle(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()).withMessage(ex.getMessage());
}

From source file:io.github.autsia.crowly.controllers.aspects.CampaignAspect.java

@Around("execution(* io.github.autsia.crowly.controllers.rest.CampaignsController.create(..))")
public Object checkCreateCampaign(ProceedingJoinPoint joinPoint) throws Throwable {
    try {/*from  www  .  j ava  2s. c o  m*/
        Object[] args = joinPoint.getArgs();
        String name = (String) args[0];
        String socialEndpoints = (String) args[1];
        String language = (String) args[2];
        String keywords = (String) args[3];
        String regionNames = (String) args[4];
        String startDate = (String) args[5];
        String endDate = (String) args[6];
        String cronExpression = (String) args[7];
        String sentiment = (String) args[8];
        float threshold = (Float) args[9];
        String emails = (String) args[10];

        boolean isNameNotEmpty = !name.isEmpty();
        boolean isSocialEndpointsCorrect = socialEndpoints.split(SEPARATOR).length != 0;
        boolean isLanguageCorrect = language.split(SEPARATOR).length != 0;
        boolean isKeywordsCorrect = keywords.split(SEPARATOR).length != 0;
        boolean isRegionNamesNotEmpty = !regionNames.isEmpty();
        boolean isStartDatNotEmpty = !startDate.isEmpty();
        boolean isEndDateNotEmpty = !endDate.isEmpty();
        boolean isCronExpressionNotEmpty = !cronExpression.isEmpty();
        boolean isSentimentCorrect = Sentiment.get(sentiment) != null;
        boolean isThresholdCorrect = threshold >= 0 && threshold <= 100;
        boolean isEmailsValid = true;
        if (emails != null) {
            for (String email : emails.split(SEPARATOR)) {
                if (!pattern.matcher(email).matches()) {
                    isEmailsValid = false;
                    break;
                }
            }
        }
        if (isNameNotEmpty && isSocialEndpointsCorrect && isLanguageCorrect && isKeywordsCorrect
                && isRegionNamesNotEmpty && isStartDatNotEmpty && isEndDateNotEmpty && isCronExpressionNotEmpty
                && isSentimentCorrect && isThresholdCorrect && isEmailsValid) {
            return joinPoint.proceed(joinPoint.getArgs());
        } else {
            throw new IllegalArgumentException();
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.bonitasoft.web.designer.controller.ResourceControllerAdvice.java

@ExceptionHandler(RepositoryException.class)
public ResponseEntity<ErrorMessage> handleRepositoryException(RepositoryException exception) {
    logger.error("Internal Exception", exception);
    return new ResponseEntity<>(new ErrorMessage(exception), HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:com.ns.retailmgr.controller.exception.RestControllerExceptionHandler.java

protected ResponseEntity<Object> handleRunTimeException(RuntimeException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {
    status = HttpStatus.INTERNAL_SERVER_ERROR;
    Throwable mostSpecificCause = ex.getCause();
    RestErrorMessage RestErrorMessage;/*  www .  j a v  a2 s  . c o  m*/
    if (mostSpecificCause != null) {
        String exceptionName = mostSpecificCause.getClass().getName();
        String message = mostSpecificCause.getMessage();
        RestErrorMessage = new RestErrorMessage(exceptionName, message);
    } else {
        RestErrorMessage = new RestErrorMessage(ex.getMessage());
    }
    return new ResponseEntity(RestErrorMessage, headers, status);
}

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;/*  ww w  . j av a2s .  c om*/

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:org.ng200.openolympus.controller.OlympusErrorController.java

@Override
public Map<String, Object> extract(final RequestAttributes attributes, final boolean b1, final boolean b2) {
    final Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {/*  www  . ja  v  a  2  s  . c  o m*/
        Throwable error = (Throwable) attributes.getAttribute("javax.servlet.error.exception",
                RequestAttributes.SCOPE_REQUEST);
        final Object obj = attributes.getAttribute("javax.servlet.error.status_code",
                RequestAttributes.SCOPE_REQUEST);
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
        } else {
        }
        map.put("status", status);
        map.put("statusPhrase", HttpStatus.valueOf(status).getReasonPhrase());
        final List<Throwable> exceptions = new ArrayList<Throwable>();
        while (error != null) {
            exceptions.add(error);
            error = error.getCause();
        }
        map.put("exceptions", exceptions);
        return map;
    } catch (final Exception ex) {
        map.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
        map.put("statusPhrase", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        map.put("exceptions", Lists.from(ex));
        return map;
    }
}

From source file:com.mum.controller.CardRestController.java

@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal server error")
public void handleServerErrors(Exception ex) {
}

From source file:com.gooddata.gdc.DataStoreService.java

private void upload(URI url, InputStream stream) {
    try {/*from  w w  w.  j  ava2  s. c om*/
        sardine.put(url.toString(), stream);
    } catch (SardineException e) {
        if (HttpStatus.INTERNAL_SERVER_ERROR.value() == e.getStatusCode()) {
            // this error may occur when user issues request to WebDAV before SST and TT were obtained
            // and WebDAV is deployed on a separate hostname
            // see https://github.com/martiner/gooddata-java/wiki/Known-limitations
            throw new DataStoreException(createUnAuthRequestWarningMessage(url), e);
        } else {
            throw new DataStoreException("Unable to upload to " + url + " got status " + e.getStatusCode(), e);
        }
    } catch (IOException e) {
        // this error may occur when user issues request to WebDAV before SST and TT were obtained
        // and WebDAV deployed on the same hostname
        // see https://github.com/martiner/gooddata-java/wiki/Known-limitations
        if (e.getCause() instanceof NonRepeatableRequestException) {
            throw new DataStoreException(createUnAuthRequestWarningMessage(url), e);
        } else {
            throw new DataStoreException("Unable to upload to " + url, e);
        }
    }
}

From source file:com.wisemapping.rest.BaseController.java

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody/*from  w w w  . j av a 2s  .  com*/
public RestErrors handleServerErrors(@NotNull Exception ex, @NotNull HttpServletRequest request) {
    final User user = Utils.getUser(false);
    notificationService.reportJavaException(ex, user, request);
    ex.printStackTrace();
    return new RestErrors(ex.getMessage(), Severity.SEVERE);
}