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:fi.helsinki.opintoni.exception.GlobalExceptionHandlers.java

@ExceptionHandler(value = Exception.class)
public ResponseEntity<CommonError> handleException(Exception e) throws Exception {
    // Only log a brief info message on broken pipes
    if (StringUtils.containsIgnoreCase(ExceptionUtils.getRootCauseMessage(e), "Broken pipe")) {
        LOGGER.info("Broken pipe occurred");
        return null;
    }/*from w  ww. j  a  va2 s.  c o  m*/

    // If the exception is annotated with @ResponseStatus, rethrow it for other handlers
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;
    }

    LOGGER.error("Caught exception", e);

    return new ResponseEntity<>(new CommonError("Something went wrong"), HttpStatus.INTERNAL_SERVER_ERROR);
}

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

@RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResourceRendering> getSwarm(@PathVariable("id") String id) {
    logger.debug("Get Swarm " + id);
    try {/*from  ww w  .j a  v a2  s . co  m*/
        return instanceService.getEntity(id, transformerManager.getTransformerProvider(TransformerType.SWARM))
                .map(swar -> new ResponseEntity<>(((Swarm) swar).getRendering(), HttpStatus.OK))
                .orElse(new ResponseEntity(HttpStatus.NOT_FOUND));
    } catch (ClientException e) {
        logger.error(this.getClass().getName(), e);
        return new ResponseEntity(e.getJsonError(), HttpStatus.BAD_REQUEST);
    } catch (ServerException e) {
        logger.error(this.getClass().getName(), e);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.sjsu.cmpe275.lab2.service.ManageOrgController.java

/** (5) Create an organization object
 *
 * Method: POST//from   w w  w.  ja v  a  2 s.  c o  m
 * This API creates an organization object.
 * For simplicity, all the fields (name, description, street, city, etc), except ID, are passed in as query
 * parameters. Only name is required.
 * The request returns the newly created organization object in JSON in its HTTP payload, including all attributes.
 * (Please note this differs from generally recommended practice of only returning the ID.)
 * If the request is invalid, e.g., missing required parameters, the HTTP status code should be 400; otherwise 200.
 *
 * @param name         Name of Organization
 * @param description   Brief description of organization
 * @param street       Address of Organization
 * @param city         Address of Organization
 * @param state         Address of Organization
 * @param zip          Address of Organization
 * @return             Created Organization
 */

@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity createOrganization(@RequestParam(value = "name", required = true) String name,
        @RequestParam(value = "description", required = false) String description,
        @RequestParam(value = "street", required = false) String street,
        @RequestParam(value = "city", required = false) String city,
        @RequestParam(value = "state", required = false) String state,
        @RequestParam(value = "zip", required = false) String zip) {
    Session session = null;
    Transaction transaction = null;
    Organization organization = new Organization();
    organization.setAddress(new Address(street, city, state, zip));
    organization.setDescription(description);
    organization.setName(name);

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        session.save(organization);
        transaction.commit();
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        return new ResponseEntity("Internal server error.", HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return new ResponseEntity(organization, HttpStatus.OK);
}

From source file:com.javafxpert.wikibrowser.WikiSearchController.java

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> search(@RequestParam(value = "title", defaultValue = "") String title,
        @RequestParam(value = "nearmatch", defaultValue = "false") boolean nearmatch,
        @RequestParam(value = "lang") String lang) {

    String language = wikiBrowserProperties.computeLang(lang);

    //TODO: Implement better way of creating the query represented by the following variables

    String qa = "https://";
    String qb = ""; // Some language code e.g. en
    String qc = ".wikipedia.org/w/api.php?action=query&format=json&list=search&srlimit=10&redirects";
    String qd = ""; // Indication that only nearmatch is desired
    String qe = "&srsearch=";
    String qf = ""; // article title so search for

    qb = language;//from  w w  w.j av a 2  s .c o m
    //qd = nearmatch.equalsIgnoreCase("true") ? "&srwhat=nearmatch" : "";
    qd = nearmatch ? "&srwhat=nearmatch" : "";
    qf = title;

    String searchQuery = qa + qb + qc + qd + qe + qf;

    SearchResponseNear searchResponseNear = queryProcessSearchResponse(searchQuery, language);

    return Optional.ofNullable(searchResponseNear).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Wikipedia title search unsuccessful",
                    HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:dk.nsi.haiba.minipasconverter.status.StatusReporter.java

@RequestMapping(value = "/status")
public ResponseEntity<String> reportStatus() {

    String manual = request.getParameter("manual");
    if (manual == null || manual.trim().length() == 0) {
        // no value set, use default set in the import executor
        manual = "" + minipasPreprocessor.isManualOverride();
    } else {//from   w ww .  ja v a  2  s  .  co m
        // manual flag is set on the request
        if (manual.equalsIgnoreCase("true")) {
            // flag is true, start the importer in a new thread
            minipasPreprocessor.setManualOverride(true);
            Runnable importer = new Runnable() {
                public void run() {
                    minipasPreprocessor.doManualProcess();
                }
            };
            importer.run();
        } else {
            minipasPreprocessor.setManualOverride(false);
        }
    }

    HttpHeaders headers = new HttpHeaders();
    String body = "OK";
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    body = "OK";

    try {
        if (!statusRepo.isHAIBADBAlive()) {
            body = "HAIBA Database is _NOT_ running correctly";
        } else if (statusRepo.isOverdue()) {
            // last run information is applied to body later
            body = "Is overdue";
        } else {
            status = HttpStatus.OK;
        }
    } catch (Exception e) {
        body = e.getMessage();
    }

    body += "</br>";
    body = addLastRunInformation(body);

    body += "</br>------------------</br>";

    String importProgress = currentImportProgress.getStatus();
    body += importProgress;

    body += "</br>------------------</br>";

    String url = request.getRequestURL().toString();

    body += "<a href=\"" + url + "?manual=true\">Manual start importer</a>";
    body += "</br>";
    body += "<a href=\"" + url + "?manual=false\">Scheduled start importer</a>";
    body += "</br>";
    if (manual.equalsIgnoreCase("true")) {
        body += "status: MANUAL";
    } else {
        // default
        body += "status: SCHEDULED - " + cron;
    }

    headers.setContentType(MediaType.TEXT_HTML);

    return new ResponseEntity<String>(body, headers, status);
}

From source file:org.esbtools.gateway.resubmit.controller.ResubmitGateway.java

@ExceptionHandler(ResubmitFailedException.class)
private ResponseEntity<ResubmitResponse> resubmitFailedExceptionHandler(ResubmitFailedException e) {
    ResubmitResponse resubmitResponse = new ResubmitResponse(GatewayResponse.Status.Error, e.getMessage());
    return new ResponseEntity<>(resubmitResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:eu.freme.common.exception.ExceptionHandlerService.java

public ResponseEntity<String> handleError(HttpServletRequest req, Throwable exception) {
    logger.error("Request: " + req.getRequestURL() + " raised ", exception);

    HttpStatus statusCode = null;/* w  ww. jav a  2 s  . c  o m*/
    if (exception instanceof MissingServletRequestParameterException) {
        // create response for spring exceptions
        statusCode = HttpStatus.BAD_REQUEST;
    } else if (exception instanceof FREMEHttpException
            && ((FREMEHttpException) exception).getHttpStatusCode() != null) {
        // get response code from FREMEHttpException
        statusCode = ((FREMEHttpException) exception).getHttpStatusCode();
    } else if (exception instanceof AccessDeniedException) {
        statusCode = HttpStatus.UNAUTHORIZED;
    } else if (exception instanceof HttpMessageNotReadableException) {
        statusCode = HttpStatus.BAD_REQUEST;
    } else {
        // get status code from exception class annotation
        Annotation responseStatusAnnotation = exception.getClass().getAnnotation(ResponseStatus.class);
        if (responseStatusAnnotation instanceof ResponseStatus) {
            statusCode = ((ResponseStatus) responseStatusAnnotation).value();
        } else {
            // set default status code 500
            statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
    JSONObject json = new JSONObject();
    json.put("status", statusCode.value());
    json.put("message", exception.getMessage());
    json.put("error", statusCode.getReasonPhrase());
    json.put("timestamp", new Date().getTime());
    json.put("exception", exception.getClass().getName());
    json.put("path", req.getRequestURI());

    if (exception instanceof AdditionalFieldsException) {
        Map<String, JSONObject> additionalFields = ((AdditionalFieldsException) exception)
                .getAdditionalFields();
        for (String key : additionalFields.keySet()) {
            json.put(key, additionalFields.get(key));
        }
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json");

    return new ResponseEntity<String>(json.toString(2), responseHeaders, statusCode);
}

From source file:ca.hec.tenjin.tool.controller.SyllabusController.java

@RequestMapping(value = "/syllabus", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<List<Syllabus>> getSyllabusList(
        @RequestParam(value = "siteId", required = false) String siteId)
        throws DeniedAccessException, NoSyllabusException {
    List<Syllabus> syllabusList = null;

    // If site from request is null, use the context
    siteId = (siteId != null ? siteId : sakaiProxy.getCurrentSiteId());
    String currentUserId = sakaiProxy.getCurrentUserId();

    try {//from   w  ww .  ja va 2 s . c  om
        // We get the syllabus list for the current site with the sections
        // associated to the user
        syllabusList = syllabusService.getSyllabusListForUser(siteId, currentUserId);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<List<Syllabus>>(syllabusList, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<List<Syllabus>>(syllabusList, HttpStatus.OK);
}

From source file:com.haulmont.idp.controllers.IdpController.java

@GetMapping(value = "/")
public String checkIdpSession(@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) {// w ww .j av  a 2 s .  c om
    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)) {
        String serviceProviderTicket = idpService.createServiceProviderTicket(idpSessionCookie);
        if (serviceProviderTicket != null) {
            String serviceProviderRedirectUrl;
            try {
                URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

                if (ResponseType.CLIENT_TICKET.getCode().equals(responseType)) {
                    uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + serviceProviderTicket);
                } else {
                    uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, serviceProviderTicket);
                }

                serviceProviderRedirectUrl = uriBuilder.build().toString();
            } catch (URISyntaxException e) {
                log.warn("Unable to compose redirect URL", e);

                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return null;
            }

            try {
                response.sendRedirect(serviceProviderRedirectUrl);
            } catch (IOException e) {
                // do not log stacktrace here
                log.warn("Unable to send redirect to service provider URL", e.getMessage());
            }

            log.debug("New ticket {} created for already logged in user", serviceProviderTicket);

            return null;
        } else {
            log.debug("IDP session {} not found, login required", 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:gateway.test.EventTests.java

/**
 * Test GET /event/* ww  w.  ja va 2s . c o  m*/
 */
@Test
public void testGetEvents() {
    // Mock Response
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenReturn(new ResponseEntity<String>("event", HttpStatus.OK));

    // Test
    ResponseEntity<?> response = eventController.getEvents(null, null, null, null, 0, 10, user);

    // Verify
    assertTrue(response.getBody().toString().equals("event"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test REST Exception
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test General Exception
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));

    // Test Validation Input Exception
    when(gatewayUtil.validateInput(anyString(), any())).thenReturn("Error");
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.BAD_REQUEST));
    assertTrue(response.getBody() instanceof ErrorResponse);
}